C++中的数字和

w8rqjzmb  于 2023-08-09  发布在  其他
关注(0)|答案(2)|浏览(93)

程序询问的是数字的总和:

  • 输入数据的格式如下:* 第一行包含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循环。
PS:我检查了其他主题,只是希望有人可以帮助我的代码,谢谢。

xytpbqjk

xytpbqjk1#

你不需要第二个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

xpszyzbs

xpszyzbs2#

#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;

}

字符串

相关问题