c++中的二维数组

2 dimensional arrays in c++

本文关键字:二维数组 c++      更新时间:2023-10-16

嗨,我现在正在解决高中c++课上的一个问题。

我们应该编写一个程序,其中包含可以存储每月最高温度和最低温度的数组。而且,程序应该有一个循环来计算以下内容:

  • 年平均高温

  • 年平均低温

  • 最高月平均高温

    • 最低月平均高温

我被每月最高和最低平均气温困扰了,可能需要一些帮助。到目前为止我的代码是:

#include <iostream>
using namespace std;
int main()
{
class location;
int high[12];
int low[12];
int i = 1;
int avgh, avgl;

//set location
std::string location;
std::cout << "Where is the location of your data:   ";
std::getline(std::cin, location);
cout << endl << endl;
//initialize array high
for (i = 1; i < 13; i++)
{
    cout << "Enter temperature high of month " << i << "    ";
    cin >> high[i];
    avgh += high[i];
}
cout << endl << endl;
//initialize array low
for (i = 1; i < 13; i++)
{
    cout << "Enter temperature low of month " << i << "    ";
    cin >> low[i];
}
cout << endl << endl;
//adds highs together
    for (i = 1; i < 13; i++)
{
    avgh += high[i];
}
cout << "The yearly average high is:   " << avgh/12 << endl;
    //adds lows together
    for (i = 1; i < 13; i++)
{
    avgl += low[i];
}
cout << "The yearly average low is:   " << avgl/12 << endl;

return 0;
}
for (i = 1; i < 13; i++)

这太错了。应该是:

for (i = 0; i < 12; i++)

c++中的索引是从零开始的。


//adds highs together
for (i = 1; i < 13; i++)
{
    avgh += high[i];
}

您已经在初始化阶段这样做了,因此这会导致错误的结果。然而,你没有对低做同样的事情,所以你可以保留低的部分。无论如何,最好在初始化时同时进行,或者分开进行,以保持统一的方式。