寻找有关如何在for语句中计算用户输入数字总和并在for循环完成后打印它的一些见解。
到目前为止,我有这段代码:
//this code will sort 2 numbers then print them in ascending order and
before exiting, add them all together
// then average them
#include <iostream>
using namespace std;
int main(int,char**) {
int n, m, z, sort1, sort2;
for (n=0;n<3;n++){
cout << " enter two integers (n n): ";
cin >> m;
cin >> z;
if (m>z){
sort1 = z;
sort2 = m;
}
else{
sort1 = m;
sort2 = z;
}
cout << sort1 << sort2 << endl;
}
int sum = m+z;
int sum2 = m+z+sum;
float sum3= m+z+sum2;
cout << " sum of all numbers entered: " << sum << endl;
cout << " average of the numberes entered: " << sum3 /6 << endl;
}
所以我知道我的sum函数是不正确的,它只评估用户输入的最后一个m + z而不是其他的。如果我将sum函数放在循环中,一旦它中断,它就会转储循环中的所有信息,使得sum值过时。想知道是否有另一种方法可以在循环中实现sum函数,但只能在循环外打印一次。
是否有其他循环不会删除循环中可以从外部提取的信息?
答案 0 :(得分:1)
C ++中的所有循环都是作用域的,这意味着在作用域内声明的任何变量都不能在作用域之外访问,也不会持续到下一次迭代。
int sum = 0; // declare sum outside of loop
for(int n = 0; 0 < 3; n++)
{
int m, z; // These will be reset every iteration of the for loop
cout << " enter two integers (n n): ";
cin >> m;
cin >> z;
/*
Sort and print goes here...
*/
sum += m + z;
}
std::cout << "The sum: " << sum <<std::endl;
答案 1 :(得分:1)
#include<iostream>
using namespace std;
int main()
{
int total = 0, i, j, sort1, sort2;
//this For-Loop will loop three times, every time getting two new
//integer from the user
for (int c = 0; c < 3; c++) {
cout << "Enter two integers ( n n ): ";
cin >> i;
cin >> j;
//This will compare if first number is bigger than the second one. If it
//is, then second number is the smallest
if (i > j) {
sort1 = j;
sort2 = i;
}
else {
sort1 = i;
sort2 = j;
}
cout << "The numbers are: " << sort1 << " and " << sort2 << endl;
//This statement will add into the variable total, the sum of both numbers entered before doing another loop around
total += i + j;
}
cout << "The sum of all integers entered is: " << total << endl;
system("pause");
return 0;
}