在C++中分离数字

Separating Digits in C++

本文关键字:数字 分离 C++      更新时间:2023-10-16

我正在编写C++书中的一个练习,我不知道如何修复它。我应该从用户那里获得一个int,并按照输入的顺序显示各个数字。例如,12345将显示1 2 3 4 5。7365将显示7 3 6 5。我已经编写了大部分代码,但有一个逻辑错误,我无法理解。这是我的代码:

int main()
{
    int number = 0;
    int digit = 0;
    int temp = 0;
    int counter = 0;
    int sum = 0;
    int divisor = 0;
    cout << "Please enter a nonzero number.";
    cin >> number;
    cout << "nThe number you entered was " << number;
    // Determine the number of digits
    temp = number;
    while (temp != 0)
    {
        temp = temp / 10;
        counter++;
    }
    cout << "nThere are " << counter << " digits in your number.";
    // Separate the digits
    temp = number;
    cout << "nSeparating the digitsn";
    do
    {
        divisor = (pow(10.0, --counter));
        digit = temp / divisor;
        temp = temp % divisor;
        cout << digit << " ";
        sum = sum + digit;
    }
    while (counter != 0);
    cout << "nThe sum of the number is " << sum;
    return 0;
}

当我输入5555时,输出为5560。当我输入1234时,输出为1236。有人能帮我找出错误吗?

这里有一个版本:

// If the number is only one digit, print it.  
// Otherwise, print all digits except the last, then print the last.
void digits(int x)
{
   if (x < 10){
      cout << x;
   }
   else{
      digits(x / 10);
      cout << " " << x % 10;
   }  
}

感谢大家的帮助:-)我的代码在另一个编译器中运行良好,所以我想这只是netbeans故障。