每次迭代后保存 For 循环值,并将这些值相加得出总计(不使用函数)

问题描述 投票:0回答:1

我真的不想在这里问这个问题,因为感觉它应该非常容易弄清楚。我绞尽脑汁想了半天,尝试了多种方法,似乎无法弄清楚。在这里发帖是最后的手段...

我有一个一维数组(非矢量)。通过 FOR 循环和嵌套 IF 语句分离偶数和奇数。它分别通过 IF 语句正确地从数组中返回正确的整数。问题是如何在 FOR 循环和/或 IF 语句中逻辑地添加每个整数迭代以获得总和。

正如标题所述,我更愿意在没有函数的情况下执行此操作。

**假设所有必要的标头都已合并,并且 Main() 和与以下代码无关的所有括号都是正确的。


int eo_array[] = { 1,2,3,4,5,6,7,8 };

cout << sizeof(eo_array) / sizeof(eo_array[0]);  //verifying the size of the array is what it should be

for (int i = 0; i < sizeof(eo_array) / sizeof(eo_array[0]); i++) {
        
    //first part of if statement is for even numbers
    if (eo_array[i] % 2 == 0) {
        
        cout << eo_array[i] << endl;
                    
    }
    //else part of if statement is for odd numbers
    else {

        cout << eo_array[i] << endl;

    }
}

输出(F5): 数组大小:8

1 2 3 4 5 6 7 8

正如您在输出中看到的那样。该程序正确显示代码中的所有数字(偶数和奇数)。如果您要注释掉 IF 或 ELSE 区域中的一个或其他 cout 语句,您还将看到相应的偶数/奇数。

尝试放置新变量来临时存储值或 eo_array,但是如果 IF 语句之前有一个声明,则该值将覆盖下一个 FOR 循环中 IF 语句中存储的任何内容。

TLDR:每次通过 FOR 循环迭代时,如何保存 eo_array 值?最终目标是将所有偶数或奇数分别加在一起并计算出最终值。

c++ arrays for-loop if-statement iteration
1个回答
0
投票
#include <stdc++.h>
//custom library added from github = has lots of headers included

using namespace std;


int main(){

int eo_array[] = { 1,2,3,4,5,6,7,8 };

cout << "Size of array: " << sizeof(eo_array) / sizeof(eo_array[0]) << endl << endl;

int eo_sumeven = 0;
int eo_sumodd = 0;


for (int i = 0; i < sizeof(eo_array) / sizeof(eo_array[0]); i++) {
            
    //first part of if statement is for even numbers
    if (eo_array[i] % 2 == 0) {
        
        eo_sumeven += eo_array[i];

        //cout << eo_array[i] << endl;
                                
    }
    //else part of if statement is for odd numbers
    else {

        eo_sumodd += eo_array[i];
        //cout << eo_array[i] << endl;

    }
            
}

cout << "The sum of even numbers in the array is: " << eo_sumeven << endl << "The sum of odd numbers in the array is: " << eo_sumodd << endl;

}
© www.soinside.com 2019 - 2024. All rights reserved.