gpt4 book ai didi

c++ - for 循环中的 SUM 函数,C++

转载 作者:行者123 更新时间:2023-11-28 01:41:34 26 4
gpt4 key购买 nike

寻找一些关于如何在 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;
}

所以我知道我的求和函数是不正确的,它只计算用户输入的最后一个 m+z,而不计算其他的。如果我将 sum 函数放入循环中,一旦它中断,它就会转储循环中的所有信息,从而使 sum 值过时。想知道是否有另一种方法可以在循环内实现求和功能,但在循环外只打印一次。

是否有任何其他循环不会删除循环内的信息,您可以在外部提取信息?

最佳答案

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;

关于c++ - for 循环中的 SUM 函数,C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46900616/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com