简体   繁体   English

我错过了什么吗?

[英]Am I missing something?

I am trying to solve a problem on a website and it won't let me through although after trying with examples of my own it works perfectly, so I assume there has to be a case where it won't work and I can't seem to find such.我正在尝试解决网站上的问题,但它不会让我通过,尽管在尝试使用我自己的示例后它可以完美运行,所以我认为必须存在它不起作用而我不能的情况好像找到这样的。

The problem is as follows: The first line is the number X for the number inputs.问题如下: 第一行是数字输入的数字 X。 The first line of each input is the number Y whereas the second line is Y whole positive numbers that have to be summed.每个输入的第一行是数字 Y,而第二行是 Y 必须相加的整个正数。 The output should be that sum.输出应该是那个总和。 Both X and Y are whole and positive numbers. X 和 Y 都是整数和正数。

My C++ code:我的 C++ 代码:

#include <iostream>

using namespace std;

int main()
{
    int no_of_inputs;
    int input;
    int table_dim;
    int val;
    int sum = 0;
    cin >> no_of_inputs;
    for (int i = 0; i < no_of_inputs; i++)
    {
        cin >> table_dim;
        for (int i = 0; i < table_dim; i++)
        {
            cin >> val;
            sum += val;
        }
        cout << sum<<endl;

    }
}

You don't reset sum between lines.您不会sum之间重置sum If you have more than 1 input the later ones will be wrong.如果您有 1 个以上的输入,则后面的输入将是错误的。

using namespace std; is a terrible habit, kick it.这是一个可怕的习惯,踢它。

You are re-declaring i in your inner loop.您正在内部循环中重新声明i That doesn't break your program, but it makes it hard to understand.这不会破坏您的程序,但会使其难以理解。

#include <iostream>

int main()
{
    int no_of_inputs;
    std::cin >> no_of_inputs;
    for (int i = 0; i < no_of_inputs; i++)
    {
        int table_dim;
        std::cin >> table_dim;
        int sum = 0;
        for (int j = 0; j < table_dim; j++)
        {
            int val;
            std::cin >> val;
            sum += val;
        }
        std::cout << sum << std::endl;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM