【发布时间】:2020-10-20 11:54:06
【问题描述】:
我有一个简单的程序可以从用户那里获得最低和最高温度,然后我必须让程序获得当天最低和最高温度的平均值。 我应该把 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];
}
}
但是第二个循环不工作,而第一个循环工作,谁能告诉我为什么第二个循环不工作?
【问题讨论】:
-
你能分享一个示例输入、你得到的输出和预期的输出吗?
-
您是否查看过标准algorithm 库中的工具,例如
std::minmax_element?
标签: c++ arrays c++11 multidimensional-array c++17