c++ - 程序挂起不循环

标签 c++ loops if-statement while-loop codeblocks

我是 C++ 的初学者。我编写了一个程序来分隔输入的整数中的数字并显示它们及其总和。然而,当循环重复时,即使编译完美,程序也会挂起。我尝试了“... while”循环和 while 循环,但问题仍然存在。我应该怎么做才能让它毫无问题地重复(向用户询问下一个整数,计算并显示结果)?任何帮助将不胜感激。

//Preprocessor directives
#include <iostream>
#include <cmath>

//Standard library
using namespace std;

//enter function main
int main()
{
int num;
int digit;
int sum = 0;
int pwr = 0;



cout << "Enter an integer: " << endl;
cin >> num;
cout << endl;
 while (num != 0 )
 {
//while loop to ask user to enter another number
cout << "The integer you entered is: " << num << endl;
cout << "The digits of " << num << " are: " << endl;

if (num < 0)
    num = -num;

    //find the highest number of 10 that divides the number

while (num / static_cast<int>(pow(10.0, pwr)) >= 10)
    pwr++;

while (num > 0)
{
    digit = num / static_cast<int>(pow(10.0, pwr));
    cout << digit << " ";
    sum = sum + digit;
    num = num % static_cast<int>(pow(10.0, pwr));
    pwr--;
}

if (pwr != -1) //Either num is 0 or there are trailing zeros in num
    while (pwr != -1)
    {
        cout << 0 << " ";
        pwr--;
    }
cout << endl;

cout << "The sum of the digits = " << sum << endl;

while (num != 0);
cout << "Enter another integer: " << endl;
cin >> num;
cout << endl;


}
 return 0;
}

最佳答案

//Preprocessor directives
#include <iostream>
#include <cmath>

//Standard library
using namespace std;

//enter function main
int main()
{

 while (true )
 {
//reset initial values every loop
int num;
int digit;
int sum = 0;
int pwr = 0;

cout << "Enter an integer: " << endl;
cin >> num;
cout << endl;
//same exit condition
if (num == 0)
    break;
//while loop to ask user to enter another number
cout << "The integer you entered is: " << num << endl;
cout << "The digits of " << num << " are: " << endl;

if (num < 0)
    num = -num;

    //find the highest number of 10 that divides the number

while (num / static_cast<int>(pow(10.0, pwr)) >= 10)
    pwr++;

while (num > 0)
{
    digit = num / static_cast<int>(pow(10.0, pwr));
    cout << digit << " ";
    sum = sum + digit;
    num = num % static_cast<int>(pow(10.0, pwr));
    pwr--;
}

if (pwr != -1) //Either num is 0 or there are trailing zeros in num
    while (pwr != -1)
    {
        cout << 0 << " ";
        pwr--;
    }
cout << endl;

cout << "The sum of the digits = " << sum << endl;
//extraneous
/*while (num != 0);
cout << "Enter another integer: " << endl;
cin >> num;
cout << endl;*/


}
 return 0;
}

关于c++ - 程序挂起不循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49624255/

相关文章:

java - Do-while 语句 Java

java - 从 JSON API 获取数据并循环放入 CSV

java - Eclipse不允许我在尝试验证用户输入时使用else语句

java - Android - 将 Arch 转换为 Decimal

c++ - 基本类型的统一初始化语法?

c++ - 有没有更快的方法来清除控制台?

java - 我无法将 String 放在字符串数组的第一个位置

Javascript 在传递的术语上隐藏/显示 div

c++ - OpenCV:在哪里可以找到 CV_WINDOW_AUTOSIZE 常量?

c++ - 双链表插入排序Bug