所要求的程序是数字的总和:
输入数据的格式如下: 第一行包含N-要处理的值的数量;然后N行将跟随描述应该由3个整数A、B、C来计算其数字和的值;对于每种情况,你需要将A乘以B,再加上C(即A*B+C(,然后计算结果的位数之和。
答案 应该有N个结果,也用空格分隔
我在C++中的代码:
#include <iostream>
using namespace std;
int main ()
{
int n, a, b, c, t, sum = 0;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a >> b >> c;
t = a * b + c;
while (t % 10 != 0)
{
sum = sum + t % 10;
t = t / 10;
}
while (t % 10 == 0)
{
sum = sum;
t = t / 10;
}
}
cout << " ";
cout << sum;
cout << " ";
return 0;
}
我很难纠正我的代码。
感谢您的帮助。
我的假设是,除了使用2 while循环之外,应该有更好的方法来编写代码。
附言:我检查了其他主题,只是希望有人能帮助我的代码,谢谢。
您不需要第二个while
循环,第一个循环应该更正为while (t != 0)
。在那之后,你计算总和的程序就可以正常工作了。
在线试用!
#include <iostream>
using namespace std;
int main ()
{
int n, a, b, c, t, sum = 0;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a >> b >> c;
t = a * b + c;
while (t != 0)
{
sum = sum + t % 10;
t = t / 10;
}
}
cout << " ";
cout << sum;
cout << " ";
return 0;
}
输入:
1
123 456 789
输出:
33
刚刚注意到,你需要N
单独的输出,而不是单个和(就像你做的那样(,所以你的程序变成这样:
在线试用!
#include <iostream>
using namespace std;
int main ()
{
int n, a, b, c, t, sum = 0;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> a >> b >> c;
t = a * b + c;
sum = 0;
while (t != 0)
{
sum = sum + t % 10;
t = t / 10;
}
cout << sum << " ";
}
return 0;
}
输入:
2
123 456 789
321 654 987
输出:
33 15
#include <iostream>
using namespace std;
int main()
{
int num = 0;
cout << "please input any number 3digits = ";
cin >> num;
int sum[] = { 0,0,0 };
sum[0] = num/100;
sum[1] = (num/10)%10;
sum[2] = num%10;
int x = sum[0] + sum[1] + sum[2] ;
cout << x << endl;
return 0;
}