c++中的二维数组
2 dimensional arrays in c++
嗨,我现在正在解决高中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];
}
您已经在初始化阶段这样做了,因此这会导致错误的结果。然而,你没有对低做同样的事情,所以你可以保留低的部分。无论如何,最好在初始化时同时进行,或者分开进行,以保持统一的方式。
相关文章:
- 将值从二维数组输出到文本文件
- 在二维数组中查找最小值和最大值?
- 移动二维数组中的字符
- 如何正确填充在堆上分配的二维数组?
- 传递二维数组时出现问题
- 具有随机数的二维数组不会更改
- 如何在C++中获取二维数组中最少的一列数?
- 如何使用用户输入变量制作二维数组?
- C++ 中动态二维数组的访问冲突
- 遍历二维数组的所有子数组
- 将二维数组的所有元素插入到一维数组中
- 在函数中传递二维数组
- 为什么指针在对二维数组进行排序时无法正常工作?
- 创建 std::string 的二维数组的最佳做法
- 如何将文本文件读取到二维数组中并以 c++ 打印
- 元素在二维数组 c++ 中的出现次数
- 执行 c++ 二维数组
- C++ 中的二维数组初始化为一个值
- 在C++中初始化第一维大小未知的二维数组
- 如何在二维数组中存储值?