计划用C来总结每个数字的整数整数、数字、计划

2023-09-11 23:11:56 作者:afflict(折磨)

int main(){
    int x;
    int sum;

    printf("Enter a positive integer: ");
    scanf("%d", &x);

    do{

        sum += (x%10);
        x=(x/10);

        if((x/10)==0){
            sum += x;
        }
    }
    while((x/10)!=0);

    printf("%d",sum);
}

嘿,我试图让这对输入的整数中添加了每个数字,而是code我使用保持返回错误的输出。会有人请帮我解决我的公式/ code,因为我不知道为什么输出不正确。

Hey, I'm trying to get this to add up each digit within the entered integer, but the code I'm using keeps returning the wrong output. Would someone please help me fix my equation/code, because I'm not sure why the output is incorrect.

推荐答案

在你的code

int sum;

未初始化。使用这样

is not initialized. use something like

int sum = 0;

请注意:局部变量不会被自动初始化[以 0 或任何],没有明确的初始化它们的内容将是垃圾。因此,使用之和+ =(X%10); 将导致的阅读之前写的情况下,产生错误的结果。

Note: local variables are not automatically initialized [to 0 or anything], without explicit initialization their contents will be garbage. Thereby, using sum += (x%10); will lead to read before-write scenario, producing wrong result.

 
精彩推荐