如何将数组传递给函数并在函数中计算一个范围内有多少个数?

时间:2010-04-24 21:21:03

标签: c++ arrays function

    #include <iostream>
    #include <fstream>
    using namespace std;
    int calculate_total(int exam1[], int exam2[], int exam3[]); // function that calcualates grades to see how many 90,80,70,60

    int exam1[100];// array that can hold 100 numbers for 1st column
    int exam2[100];// array that can hold 100 numbers for 2nd column
    int exam3[100];// array that can hold 100 numbers for 3rd column 

// here i am passing an array into the function calcualate_total
    int calculate_total(exam1[],exam2[],exam3[])
    {
     int above90=0, above80=0, above70=0, above60=0;
     if((num<=90) && (num >=100))
     {
      above90++;
      {
       if((num<=80) && (num >=89))
       {
        above80++;
        {
         if((num<=70) && (num >=79))
         {
          above70++;
          {
           if((num<=60) && (num >=69))
           {
            above60++;
           }
          }
         }
        }
       }
      }
     }
    }

3 个答案:

答案 0 :(得分:3)

而不是使用嵌套if。 使用if,else if和else。 您的程序将是干净的,并将帮助其他人更好地阅读。

看起来您正在尝试创建频率表。 不幸的是,逻辑代码是错误的。 当您使用&& AND时 这意味着它必须满足这两个条件。 一个数字如何能够同时大于或等于90 大于或等于100 ? 可能正是您正在寻找的是||,即OR。

最后你需要一个循环

答案 1 :(得分:1)

通过指向int数组的指针。 (这里是定义)

int calculate_total(int *exam1, int *exam2, int *exam3)

如果要调用此函数,则必须在每个参数中推送examX数组的地址。如果你想要get元素,你必须添加到凝视数组地址,元素偏移地址并从她那里获取值。

答案 2 :(得分:0)

使用矢量。 你可以像数组一样初始化一个向量。 向量有一个方法来给你元素的数量