我有一个简单的程序可以从用户获取最低和最高温度,然后必须使该程序获取当天最低和最高温度的平均值。
我应该将7days,low,high放在一个名为temp`temp [7 [2] = {0};的二维数组中。
所以我编写了程序,并且运行良好,这就是代码;
//declare arr & varaibles
int temp[7][2]={0}; // temperature array
double totalHigh=0,totalLow=0; //total low temp days & total high temp days
int high=temp[0][0],low=temp[0][0];// assign the first row & column in array to get the highest & lowest number
for(int row=0;row<7;row+=1){ // for loop to get through every row
cout << "Day " << row+1 << endl;
cout << "Low: "; cin >> temp[row][0]; // first column is for low temp days
totalLow += temp[row][0] ; // get the total low days from the user
cout << "High: "; cin >> temp[row][1]; // second column is for high temp days
totalHigh += temp[row][1]; // get the total high days from the user
}
for(int j=0;j<7;j+=1){ // go through first column to get the high number of it
if(high < temp[j][0]){
high = temp[j][0];
}
}
for(int j=0;j<7;j+=1){ // go though second column to get the low number of it
if(low > temp[j][1]){
low = temp[j][1];
}
}
//display on screen
cout << fixed<< setprecision(2);
cout << "Low: "<< totalLow/7 << endl; //get the average of low
cout << "High: " <<totalHigh/7 << endl;// get the average of high
cout << "Lowest Of High column: " << low << endl;
cout << "Highst Of Low column: " << high << endl;
但是我也应该获得最高的低列数和最低的高列数。我得到的高栏数最少,但是当我使循环得到最低的数时那是行不通的。
这是遍历每一列并获取它们的两个循环的代码;
for(int j=0;j<7;j+=1){ // go through first column to get the high number of it
if(high < temp[j][0]){
high = temp[j][0];
}
}
for(int j=0;j<7;j+=1){ // go though second column to get the low number of it
if(low > temp[j][1]){
low = temp[j][1];
}
}
但是第二个循环在第一个循环工作时不起作用,有人可以告诉我为什么第二个循环不工作吗?
最佳答案
这里的问题是您将low
初始化为0
。
首次初始化2d数组时,所有值都设置为0。然后将low
初始化为temp[0][0]
,这意味着low
现在是0
。除非您的最低最高价实际上低于0,否则它将永远不会更新。
同样,如果您的最高低点低于0,您也会注意到high
也无法正常工作。
解决该问题的一种方法是,只有在用户已经输入所有数据之后才初始化high
和low
。和init high = temp[0][0], low = temp[0][1]
关于c++ - 如何在C++中获得二维数组中一列的最低数目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62653027/