用C ++分隔数字

时间:2014-09-28 22:03:54

标签: c++

我正在从我的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 digits\n";
    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.任何人都可以帮我找到我的错误吗?

2 个答案:

答案 0 :(得分:0)

这是一个版本:

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

答案 1 :(得分:0)

谢谢大家的帮助:-)原来我的代码在另一个编译器中运行正常,所以我猜它只是一个netbeans故障。