将整数分成数字,反向打印,并打印数字C ++的总和

时间:2016-12-04 21:36:34

标签: c++

我的问题是我必须使用用户给出的5位整数输入,并将整数分成各自的数字。然后我需要以相反的顺序打印这些数字,并打印出这些数字的总和。这是我到目前为止编码的将5位整数分成各个数字的代码。请注意,我只能使用整数除法和模运算符将整数分成数字。

#include <iostream>

using namespace std;
int main() {
int number;

    cout << "Enter a five-digit number: ";
    cin >> number;

    cout << number / 10000 << " ";
    number = number % 10000;
    cout << number / 1000 << " ";
    number = number % 1000;
    cout << number / 100 << " ";
    number = number % 100;
    cout << number / 10 << " ";
    number = number % 10;
    cout << number << endl;

    return 0;
}

例如,当用户输入一个5位数字(如77602)时,程序应将其输出为

7 7 6 0 2,数字之和为22。

如何以相反的顺序打印这个以及各个数字的总和?

编辑:很少拼写和语法错误。

3 个答案:

答案 0 :(得分:1)

使用代码中相同逻辑和工具的简单解决方案..

    int sum = 0;
    for(int i = 0; i < 5; ++i)
    {
        int digit = number % 10;
        sum += digit;
        cout << digit << " ";
        number /= 10;
    }

    cout << "\nSum of digits: " << sum << "\n";

答案 1 :(得分:1)

这可能是您最容易理解的解决方案:

 #include <iostream>

using namespace std;
int main()
{
int number;
int number2;
int numberReverse;
int sum = 0;

cout << "Enter a five-digit number: ";
cin >> number;

numberReverse = number;

cout << number / 10000 << " ";
sum = sum + number/10000;
number = number % 10000;
cout << number / 1000 << " ";
sum = sum + number/1000;
number = number % 1000;
cout << number / 100 << " ";
sum = sum + number/100;
number = number % 100;
cout << number / 10 << " ";
sum = sum+number/10;
number = number % 10;
cout << number << endl;
sum = sum+number;

cout << "Reverse: " << endl;

number2 = numberReverse%10;
cout << number2 << " ";
number2 = (numberReverse/10)%10;
cout << number2 << " ";
number2 = (numberReverse/100)%10;
cout << number2 << " ";
number2 = (numberReverse/1000)%10;
cout << number2  << " ";
number2 = (numberReverse/10000)%10;
cout << number2 << endl;

cout << "Sum is " << sum;

return 0;
}

答案 2 :(得分:0)

我想,你需要做这样的事情:

int number;

... some IO operations ...

std::vector<int> digits;
do {
    digits.push_back(number % 10);
    number /= 10;
} while (number);

在此之后,您需要做的就是通过向量digits

进行2-3次循环
for (std::size_t k = digits.size() - 1; k >= 0; --k)
   std::cout << digits[k] << " ";
std::cout << std::endl;
for (std::size_t k = 0; k < digits.size(); ++k)
    std::cout << digits[k] << " ";
std::cout << std::endl;
int sum = 0;
for (std::size_t k = 0; k < digits.size(); ++k)
    sum += digits[k];
std::cout << sum;