首页 > 解决方案 > 如何将一个函数中的值用于主函数?

问题描述

struct Month {
  string month;
  float avg;
};

float calMonth1() {
  float sum;
  int i;
  Month month1;
  //month 1
  cout << "Weekly Dengue Case for Month of: ";
  cin >> month1.month;

  int n = 4;
  int * week = new int[n];

  for (i = 0; i < n; ++i) {
    cout << "Week " << i + 1 << ": ";
    cin >> week[i];
    sum += week[i];
  }

  month1.avg = sum / i;
  int firstWeek = week[0];

  cout << "Average for " << month1.month << ": " << month1.avg;
  return month1.avg;
}

float calMonth2() {
  int i;
  float sum;
  Month month2;
  //month 2
  cout << "Weekly Dengue Case for Month of: ";
  cin >> month2.month;

  int n = 4;
  int * week = new int[n];

  for (i = 0; i < n; ++i) {
    cout << "Week " << i + 1 << ": ";
    cin >> week[i];
    sum += week[i];
  }

  month2.avg = sum / i;

  cout << "Average for " << month2.month << ": " << month2.avg;
  return month2.avg;
}

int main() {
  int firstWeek;
  calMonth1();
  calMonth2();

  cout << "\nInformation for first week of January, total of " << firstWeek << " cases:\n";

  return 0;
}

这是我的代码。我想要做的是在我的主函数中使用 calMonth1 函数中的 firstWeek 。我怎么可能做到这一点?我只想使用 calMonth1 中数组的第一个值。

示例输出:

第 1 周:10 第 2 周:20 第 3 周:30 第 4 周:40

1月第一周的信息,共10例:

我只希望第一周的值在上述消息中显示。谢谢

标签: c++function

解决方案


推荐阅读