使用未声明的标识符'数据' C ++

时间:2018-03-21 08:16:04

标签: c++

  

"编写一个名为sums()的函数,它有两个输入参数;一系列花车;和整数,   n,这是存储在数组中的值的数量。计算数组中正值的总和   和负值的总和。还要计算每个类别中的值的数量。归还这四个   通过输出参考参数回答。

     

编写一个主程序,读取不超过10个实数并将它们存储在一个数组中。输入0时停止读取数字。调用sums()函数并打印它返回的答案。还计算并打印正负集的平均值。"

#include <iostream>
using namespace std;

void sums(float data[], int count, float& posSum, int& posCnt, float& negSum, int& negCnt);
double input(double UserInput);

int main()
{
    float data[10];
    int count = 10 ;
    double UserInput = 0;
    float posSum=0.0, negSum=0.0; //sum of positives and negatives
    int posCnt =0, negCnt=0; // count of postive and negatives

    input(UserInput);
    sums(data, count, posSum,posCnt, negSum, negCnt);

    cout << "Positive sum: " << posSum << endl;
    cout << "Positive count:" << posCnt << endl;
    cout << "Negative sum: " << negSum << endl;
    cout << "Negative count:" << negCnt << endl;
    return 0;
}

double input(double UserInput) {
    for(int i = 0; i < 10; i++){
        cout << "Enter a real number or '0' to stop: " ;
        cin >> UserInput;
        if(UserInput == 0)break;

        data[i] = UserInput;
    }
    return UserInput;
}

void sums(float data[], int count, float& posSum, int& posCnt, float& negSum, int& negCnt){

    int i;
    for(i = 0; i < count; i++){
        if(data[i] > 0){
            posCnt += 1;
            posSum += data[i];
        }
        else{
            negCnt += 1;
            negSum += data[i];
        }
    }
}

在尝试编译时,它给我一个错误说&#34;使用未声明的标识符&#39;数据&#39;&#34;在输入函数的第32行。

1 个答案:

答案 0 :(得分:1)

这是因为数据未在函数input中声明,您应该使用float指针。

void input(float *data)
{
   float UserInput;
   for (int i = 0; i < 10; i++) 
   {
      cout << "Enter a real number or '0' to stop: ";
      cin >> UserInput;
      if (UserInput == 0)break;

      data[i] = UserInput;
  }
  return;
}

int main()
{
   float *data;

   data = (float*)malloc(10 * sizeof(float));
   input(data);

   cout << data[0];

   free(data);
   system("pause");
  return 0;
}

这应该是一个准确的例子。祝你好运,做好以下作业。