Click here to Skip to main content
15,894,343 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
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;
}
Posted
Updated 5-Jan-17 1:47am
Comments
Philippe Mori 5-Jan-17 9:01am    
Something like that would works : sum = num > 0 ? (num + 8) % 9 + 1 : 0;

This line declares the variables num, sum, and a and initialises a with zero but the value of num and sum is undefined.
int num,sum,a=0;

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;
 
Share this answer
 
Quote:
i think this code is mathematically correct
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.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900