【发布时间】:2021-12-25 09:12:05
【问题描述】:
我需要计算从用户那里得到的有理数的位数。 问题是即使代码中没有错误,程序也只运行了部分代码。我在 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;
}
【问题讨论】:
-
“有理数”不是整数的同义词。
1/2是有理数,但不是整数。请注意,在while循环期间,您永远不会修改a,因此循环条件评估的值永远不会改变;因此循环永远不会终止。
标签: c++ visual-studio