我正在编写代码来添加数字例子153 =(1 + 5 + 3)= 9 [英] I am writing code to add digits exampe 153=(1+5+3)=9
问题描述
我认为这段代码在数学上是正确的......但是当我运行这段代码时......程序总是给出一些尴尬和相同的数字...我很困惑,我试过这段代码现在..plz告诉我有什么问题..
ps:iam初学者
我尝试了什么:
#include< iostream>
使用命名空间std;
int main()
{
int num,sum,a = 0;
cin> > num;
while(num> 0)
{
a = num%10;
sum = sum + a;
num = num / 10;
}
cout<< sum<< endl;
返回0;
}
i think this code is mathamatically correct ....but when i run this code ...the programm give some awkward and same number all the time ...i am getting confused ,i have tried this code a number of times now..plz tell me what is wrong ..
ps: iam beginner
What I have tried:
#include <iostream>
using namespace std;
int main()
{
int num,sum,a=0;
cin>>num;
while(num>0)
{
a=num%10;
sum=sum+a;
num=num/10;
}
cout<<sum<<endl;
return 0;
}
推荐答案
此行声明变量num
,sum
和a
并初始化a
零,但值num
和sum
未定义。
This line declares the variablesnum
,sum
, anda
and initialisesa
with zero but the value ofnum
andsum
is undefined.
int num,sum,a=0;
虽然 num
和 a
稍后按代码分配,没有赋值给 sum
但是使用了实际值。
所以你应该把代码更改为(在这里分成多行):
While num
and a
are assigned later by code, there is no value assigned to sum
but the actual value is used.
So you should change your code to (splitted into multiple lines here):
int num = 0;
int sum = 0;
int a = 0;
i认为这段代码在数学上是正确的
i think this code is mathematically correct
如果结果是错误的,那么程序在某处是错误的。调试器将显示您的程序实际正在做什么。
您应该学习尽快使用调试器。而不是猜测你的代码在做什么,现在是时候看到你的代码正在执行并确保它能达到预期的效果。
Debugger - 维基百科,免费的百科全书 [ ^ ]
掌握Visual Studio 2010中的调试 - 初学者指南 [ ^ ]
调试器在这里向您展示您的代码正在做什么以及您的任务是与它应该做的比较。
调试器中没有魔法,它没有发现错误,它只是帮助你。当代码没有达到预期的效果时,你就会接近一个错误。
If the result is wrong, the program is wrong, somewhere. The debugger will show you what your program is really doing.
You should learn to use the debugger as soon as possible. Rather than guessing what your code is doing, It is time to see your code executing and ensuring that it does what you expect.
Debugger - Wikipedia, the free encyclopedia[^]
Mastering Debugging in Visual Studio 2010 - A Beginner's Guide[^]
The debugger is here to show you what your code is doing and your task is to compare with what it should do.
There is no magic in the debugger, it don't find bugs, it just help you to. When the code don't do what is expected, you are close to a bug.
这篇关于我正在编写代码来添加数字例子153 =(1 + 5 + 3)= 9的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!