编写一个程序,提示用户输入一个整数,然后输出数字的单个数字和数字的总和
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
例如:输入: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++编程了,代码中可能会有一些小错误,但你已经大致了解了。
相关文章:
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 如何获取一个数字的前3位
- 我想做一个彼此不同但重复出现的数字
- 如何检查一个c++字符串中有多少相同的字符/数字
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 将向量之间的数字放在另一个向量之间<vector>>如果两个数字的差值为 1
- CIN 仅在输入非数字值时跳过下一个 CIN
- 以C++输出一个数字三角形
- 形成一个斐波那契三角形,使得每个数字是上面左对角线或右对角线上两个数字的总和
- 为什么当我输入一个被接受的数字时,我的 do-while 循环没有中断?
- 一个C++程序,用于在输入位数时输出具有特定位数的 .txt 文件中的所有数字
- 在C++中编程,将 3 个数字发送到一个函数,然后计算这 3 个数字的平均函数
- 在使用堆栈为下一个最大数字编写代码时面临 SIGSEGV(分段错误)
- 找到 x^n 的所有组合,并检查它们的总和是否等于一个不包括相同数字的数字
- 是否有一个 std::set 函数来确定不超过数字 x 的最大元素?
- 将数字提高到一个巨大的指数
- 反转一个数字程序不起作用,为什么?
- 使用带有一个参数函数的递归找到数字的平方
- 为什么当我输入一个大数字时,输出会一遍又一遍地重复?
- 为什么断点显示数组的第二个值是一个大数字?额外学分工作