I need to calculate the digits of a rational number that I get from the user. The problem is that even though there is no errors in the code, the program running only part of the code. I'm working in Visual Studio.
int sumDigits(int a);
// main function
int main()
{
int ratioNum;
// Ask from the user to enter a rational number
cout << "Hello" << endl;
cout << "Please enter a rational number: ";
// Get the number from the user
cin >> ratioNum;
// Inform the user what is the sum of the digits
cout << "The sum of the digits are: " << sumDigits(ratioNum) << "." << endl;
return 0;
}
// Definition of function
int sumDigits(int a)
{
int digit = 0, sum = 0;
// As long as number is bigger than 0, continue
while (a > 0)
{
// Define a new verible - digit, as a number mudolo 10
digit = a % 10;
}
// kick out the units digit that we used
a / 10;
// Sum the digits of the number
sum = digit a;
// Return sum to the main function
return sum;
}
CodePudding user response:
You need a /= 10
instead of a / 10
, and you need it inside the loop. Otherwise the loop will run forever because a
never gets modified inside of it, so it can never become 0
.
This will fix the infinite looping issue but the result will still not be correct. Why that is would be a different question though, and I'd invite you to learn proper debugging first (google how to debug C)! This will help you a lot more than copying a solution from here.
CodePudding user response:
Your code isn't running the whole program because of these lines:
while (a > 0)
{
// Define a new verible - digit, as a number mudolo 10
digit = a % 10;
}
Inside the while loop, you're only assigning the value to the digit
variable, but not changing the value of a
, so the value of a
always remains greater than 0
. So your code gets stuck inside the while loop.
CodePudding user response:
You should write
// kick out the units digit that we used
a /= 10;