Analyzing ten integers and

Procedures require: 10 reads integer n and the sum of all outputs, and the sum of all negative integers and. This one-time user input 10 integer, and any order can be employed. Program should not require user input individual positive and negative numbers.

Analysis: The following information from the above that the subject
a user inputs a positive or negative integer ten, one-time output.
And the number of second output n-
3 and the negative output
4 output integers and

So you can learn to use a parameter to record how many times the value of his output, to determine the value of the user whether the 10 output from the first message. Here you can use the do ... while () loop to do this problem.
code show as below:

int a, b = 0, c = 0, d = 0, e = 0, k = 0; // a user to input values, b is a positive number and the sum, c is the sum of negative, d is an integer and the sum, e is an integer number of times of execution, k is an error message.

	do
	{
		e++;//整数执行次数
		cin >> a;

		if (cin.fail()) {//判断是否不为整数,如果不为整数,执行次数代码
			cin.clear();//重置cin状态;
			cin.sync();//同步
			cin.ignore();//忽略掉缓存中的内容

			e--;//减去刚刚加了的整数执行次数
			k++;//记录不为整数的次数
		}

		if (a >= 0) {
			b += a;//判断a大于等于0时,把a加给b作为正数之和
		}

		else if (a < 0) {
			c += a;//判断a小于0的时候,把a加给c作为负数之和
		}
		//d += a;//所有整数之和(不执行此处代码原因是执行次数过多,不如直接拿正数之和与负数之和的最终结果相加得到结果更加快)
	} while (e < 10);

	d = b + c;//此处计算整数之和减少了9次计算。更为优化。

	cout << "有" << k << "个字符不为整型" << endl;
	cout << "正数之和:" << b << endl;
	cout << "负数之和:" << c << endl;
	cout << "所有整数之和:" << d << endl;

Results are as follows:Here Insert Picture Description

Guess you like

Origin blog.csdn.net/qq_39686486/article/details/90292984