HUD-1095 、HUD-1096 水题对比研究(c++)

HUD-1095 、HUD-1096 水题对比研究

//写在前面。
可能有人在HUD-1095的代码基础上做改进,然后得到一个貌似能解决HUD-1096的代码,结果却总发现Presentation Error。据我观察,其实这是因为一个 空行 是否准确的问题。且听我细细道来。

————————————————————————————————————————————
//HUD-1095
Your task is to Calculate a + b.
Input
The input will consist of a series of pairs of integers a and b, separated by a space, one pair of integers per line.

Output
For each pair of input integers a and b you should output the sum of a and b, and followed by a blank line.

//下面是示例输入输出
Sample Input

1 5
10 20

Sample Output

6

30

请注意这一行,这是一行空行,在HUD-1096并不需要输出这一行。
这就是很多人把HUD-1096做错的原因。

//代码如下

#include <iostream>
using namespace std;

int main()
{
	int a,b, j, i = 0;
	while (cin >> a)
	{
		
		int s = a;
		cin >> b;
		s += b;
	    cout << s << endl;
		cout << endl;
	}
}


————————————————————————————————————————————
//HUD-1096
Your task is to calculate the sum of some integers.

Input
Input contains an integer N in the first line, and then N lines follow. Each line starts with a integer M, and then M integers follow in the same line.

Output
For each group of input integers you should output their sum in one line, and you must note that there is a blank line between outputs.

//下面是示例输入输出
Sample Input

3
4 1 2 3 4
5 1 2 3 4 5
3 1 2 3

Sample Output

10

15

6

//下面是错误代码

#include <iostream>
using namespace std;

int main()
{
	int n;
	cin >> n;
	while(n--)
	{
		int r, s = 0;
		int a;
		cin >> r;
		for (int i = 0; i < r; i++)
		{
			cin >> a;
			s += a;
		}
		
	    cout << s << endl;
	}
}

仔细观察,你会发现这个代码和HUD-1095是同一个套路。

//下面是正确代码

#include <iostream>
using namespace std;

int main()
{
	int n;
	cin >> n;
	while(n--)
	{
		int r, s = 0;
		int a;
		cin >> r;
		for (int i = 0; i < r; i++)
		{
			cin >> a;
			s += a;
		}
		if (n != 0)
		{
			cout << s << endl;
			cout << endl;
		}
		else cout << s << endl;
		
	}
}

//注意这些代码,即是解决问题所在。

if (n != 0)
		{
			cout << s << endl;
			cout << endl;
		}
		else cout << s << endl;
		

//谢谢阅读。

猜你喜欢

转载自blog.csdn.net/weixin_43655282/article/details/89043544
HUD