计划用C来总结每个数字的整数 [英] Program in C to sum each digit in an integer

查看:152
本文介绍了计划用C来总结每个数字的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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.

这篇关于计划用C来总结每个数字的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆