c - 在没有数组或函数的情况下以相反的顺序打印数字的数字

标签 c string integer

作为家庭作业,我正在研究从 stdin 读取一个 decimal int,将其转换为不同的基数(也由 stdin 提供)并将其打印到屏幕上。

这是我到目前为止所得到的:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int num, base, remainder, quotient;
    printf("please enter a positive number to convert: ");
    scanf("%d", &num);
    printf("please enter the base to convert to: ");
    scanf("%d", &base);

    remainder = quotient = 1;

    // validate input
    if (num < 0 || base < 0) {
        printf("Error - all numbers must be positive integers!\n");
        return 1;
    }

    // keep dividing to find remainders
    while (quotient > 0) {
        remainder = num % base;
        quotient = num / base;
        num = quotient;
        if (remainder >= 10) {
            printf("%c", remainder + 55);
        } else {
            printf("%d", remainder);
        }
    }   
    printf("\n");
    return 0;
}   

这很好用,只是它使用的算法计算从最低有效位到最高有效位的转换数字,从而反向打印它。因此,例如,将 1020 转换为十六进制 ( 0x3FC ) 将打印 CF3

有没有我可以用来反转这些数字以正确顺序打印的技巧。我只能使用 if-else、while、简单的数学运算符和 printf()/getchar()/scanf()——不能使用函数、数组或指针。谢谢。

最佳答案

(这里删除了帖子的原始部分,因为它不是解决方案)

然后我能看到的唯一解决方案是执行你现在拥有数字的次数的循环。

所以,首先你计算所有数字直到你到达最后一个,然后打印它。

然后你取原始值 + 基数并再次开始除法直到你来到第二个“最高值”数字,然后打印它。

这是一个双循环,您计算所有内容两次,但不使用额外的存储空间。

关于c - 在没有数组或函数的情况下以相反的顺序打印数字的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1957647/

相关文章:

java - 为什么我的 List<Integer> 中的元素是字符类型?

string - 在 MATLAB 中将元胞数组转换为字符串

Java加密: encrypt integer values

c#将表达式中的字符串转换为int

c - C unix 中的文件配置、创建和使用

c# - += 使用字符串的相反操作是什么?

string - 加速计算字母表中没有长度 > 1 的重复子串的字符串数

c - 为什么会发生堆损坏?

c - 根据给定顺序订购字符串数

c - 关于 C 中 getchar() 的问题?