gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:02:47 25 4
gpt4 key购买 nike

作为家庭作业,我正在研究从 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com