mardi 3 avril 2018

Program hangs and does not loop

I am a beginner in c++. I wrote a program to separate the digits in an integer entered and display them and their sum. However, when the loop repeats, the program hangs even though it compiled perfectly. I tried a '... while' loop and a while loop but the problem persists. What should I do to have it repeat (ask user for next integer, calculate and display the results) without problems? Any help will be appreciated.

//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;
}

Aucun commentaire:

Enregistrer un commentaire