c - 数字总和程序无法为更大的数字提供正确的 O/P

标签 c scanf

我编写了一个程序来求数字之和。当我使用数字(例如 10 位数字)时,我会得到一些错误的答案。

例如,如果我将输入指定为 9999999999,则输出为 46。以下是到目前为止我的代码:

#include<stdio.h>

int main()
{
    int sum,value,rem;
    printf("Enter the value:");
    scanf("%d",&value);
    sum= 0;
    while((value/10)>0)
    {
        rem=value%10;
        sum=sum+rem;
        value=value/10;
    }
    sum=sum+value;
    printf("Sum of digits is %d",sum);
    return 0;
}

最佳答案

9999999999 的值太大,无法由 int 保存。

引用:C11 标准,第 §5.2.4.2.1 章,

INT_MAX                 +32767
UINT_MAX                 65535
LONG_MAX                +2147483647
ULONG_MAX                4294967295
LLONG_MAX               +9223372036854775807
ULLONG_MAX               18446744073709551615

尝试使用更大数据类型,例如long long intunsigned long long int。您应该为所使用的数据类型使用适当的转换说明符。

请注意,main() 的推荐签名是 int main(void)

关于c - 数字总和程序无法为更大的数字提供正确的 O/P,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30371196/

相关文章:

c - 我如何将这个ipv6地址分配给c中的sscanf?

c - Fork数组赋值冲突

有人可以告诉我为什么会出现这个运行时错误吗?

c - 如何删除 C 中的以下 lint 警告?

代码从 C 文本文件中读取几行

c - 仅通过 EOF 结束 while 循环一次

c - `sscanf` 是否保证不更改它找不到的参数?

c - (C) 将std in解析成链表,无限循环

c - c编程输出信息错误

c - libgcrypt-config --libs : no such file or directory