编写一个程序,提示用户输入一个整数,然后输出数字的单个数字和数字的总和

Write a program that prompts the user to input an integer and then outputs both the individual digits of the number and the sum of the digits

本文关键字:数字 一个 输出 单个 然后 提示 程序 用户 输入 整数      更新时间:2023-10-16

例如:输入:982

输出:9 8 2您的总金额是:19

我看到人们在循环中使用input_number%10,然后使用input_nnumber/10,但我仍然没有得到它。如果我使用982%10,我会得到2,然后他们将其添加到0+2=2的总和中,这怎么会得到19????然后输入的数字982/10等于9.82,如何得出19的解??我只是非常困惑,有人能给我解释一下,试着解决这个问题,把它变成一个简单的解决方案吗。我很感激,并尝试使用基本的东西,比如包括命名空间std,然后不使用数组,只使用循环和简单的数学方程,谢谢。

int n,sum=0;
cin>>n;
while(n!=0)
{
sum=sum+(n%10);
n=n/10;   
}
/*
Since your n is an integer it will drop the value after decimal. 
Therefore, 982 will run as
Iteration 1 n=982
sum=2
n=982/10=98
Iteration 2
sum=2+(98)%10 = 10
n=98/10= 9
Finaly in iteration 3 
n=9/10=0 hence loop will terminate and sum be 19*/

您应该将数字作为字符输入,然后将其转换为数字,然后再转换为易于添加或打印的单个数字。避免复杂的数学,当你可以完全没有它。

std::string str;
std::cin >> str;
int sum = 0;
for( int i=0; i<str.length(); i++) {
if( isdigit(str[i]) ) {
std::cout << str[i] << " ";
sum += int(str[i] - '0')  // convert a char to int
}
}
std::cout << std::endl;
std::cout << "Total sum: " << sum << std::endl;

或者类似的东西。有一段时间没有用C++编程了,代码中可能会有一些小错误,但你已经大致了解了。

相关文章: