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

标签 c++ loops for-loop sum

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

相关文章:

Python:简单 OLS super 词典

c++ - 给定均匀随机数生成器生成随机数

c++ - C++:从程序,Windows和Linux中测量内存使用情况

c - 数组 get 被 while 循环覆盖,它们都具有相同的数据

javascript - for 循环中出现意外值

python - 有没有办法设置可选参数来绕过输入参数?

c++ - 在代码中使用#ifdef 是一种不好的做法吗?

C++ 最小最大失败

android - 使用 android 媒体播放器重复播放音乐一定 x 次

python-3.x - 打印_的刽子手游戏问题???逻辑问题,我想