c - 当输入数字太大时,C 程序无法运行

标签 c algorithm memory memory-management types

我用 C 编写了一个程序,打印代表输入数字的英文(逐位数字) 例如,当您输入938时,它将打印出九三八 当输入太大(超过 9 位)时,它不起作用。 谁能向我解释为什么会发生这种情况? 我尝试过使用 unsigned int 而不是 int 作为变量,但仍然不起作用。

#include <stdio.h>
/**
10/17/2012
Programming in C
Ch6 no. 6
Program doesn't work when number gets too large (>9 digits)
Print english that represents input number (digit by digit)
*/

int main(void){

int digit;//use to hold digit

int number;//hold input number

int revNumber = 0; //the reversed digit of the input number

int no_zero = 0;//number of zero needed to be printed at the end

int i = 1;//hold how many digits does the number have (+1 = i*10)

printf("Please enter a number\n");

scanf("%u", &number);

int testing = number;//a copy of input number for

//counts how many digits does the number have (+1 = i*10)

for(; testing != 0;i *= 10){

    testing /= 10;

}

//make the reversed number

do{

    i /= 10;

    digit = number % 10;

    if(digit == 0)

        no_zero++;

    revNumber += (digit*i);

    number /= 10;

}while(number != 0);


//print the result using the reversed number

do{

    digit = revNumber % 10;

    revNumber /= 10;

    switch(digit)

    {

     case 0:

     printf("zero ");

     no_zero--; //minus zero not at the end

     break;

     case 1:

     printf("one ");

     break;

     case 2:

     printf("two ");

     break;

     case 3:

     printf("three ");

     break;

     case 4:

     printf("four ");

     break;

     case 5:

     printf("five ");

     break;

     case 6:

     printf("six ");

     break;

     case 7:

     printf("seven ");

     break;

     case 8:

     printf("eight ");

     break;

     default:

     printf("nine ");

    }

}while(revNumber != 0);


//add back the ending zero

for(;no_zero!=0;no_zero--)

printf("zero ");

return 0;

}

最佳答案

C 中 int 的标准表示是有限的。基本上,您有 8 * sizeof (int) 位可用(假设 32)。由于有 32 位可用,unsigned int 可以大到 2^32 - 1,即 4294967295 任意大于这个数字是不行的。

您可以尝试使用unsigned long long,但这仍然受到限制。或者,您可以尝试使用 BigNum图书馆。

但是,对于您的具体问题,将数字作为字符串读取并对该字符串的每个字母进行操作就足够了。

关于c - 当输入数字太大时,C 程序无法运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12928060/

相关文章:

java - 如何检测在 Netbeans 中进行分析时未显示的内存泄漏?

您可以使用 objdump 在函数中找到局部字符数组的内存吗?

c++ - 使用FFmpeg以编程方式创建视频,使用SDL的 Sprite 截图BMP

c - 如何跨多行、空格等读取用户输入?

algorithm - 在常数时间内复制一个字符串?

python - 在递归中使用 yield 平衡内存和性能

java - 如何在一个长的for循环中清空所有变量,避免程序内存不足?

C- 在很长的系列中找到数字的最佳技巧是什么

c++ - C++ 中的 23 位用户定义类型

algorithm - 如何在高维数据中高效寻找k近邻?