【问题标题】:Why isn't my code running the whole program but not producing any errors?为什么我的代码没有运行整个程序但没有产生任何错误?
【发布时间】: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


【解决方案1】:

你应该写

// kick out the units digit that we used
    a /= 10;

【讨论】:

  • 钢不工作
【解决方案2】:

您需要a /= 10 而不是a / 10,并且您需要它在循环中。否则循环将永远运行,因为a 永远不会在其中被修改,所以它永远不会变成0

这将解决无限循环问题,但结果仍然不正确。为什么那将是一个不同的问题,我会邀请您首先学习正确的调试(谷歌如何调试 C)!这将比从这里复制解决方案对您有更多帮助。

【讨论】:

  • @MinxinYu-MSFT 那么你应该评论这个问题而不是我的答案。
【解决方案3】:

由于这些行,您的代码没有运行整个程序:

while (a > 0)
{
    // Define a new verible - digit, as a number mudolo 10
    digit = a % 10;
}

在 while 循环中,您只是将值分配给 digit 变量,而不是更改 a 的值,因此 a 的值始终保持为 greater than 0。所以你的代码会卡在 while 循环中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 2020-04-08
    • 2019-06-17
    • 1970-01-01
    • 2013-08-05
    • 1970-01-01
    相关资源
    最近更新 更多