c++ - 如何在C++中获得二维数组中一列的最低数目?

标签 c++ arrays c++11 multidimensional-array c++17

我有一个简单的程序可以从用户获取最低和最高温度,然后必须使该程序获取当天最低和最高温度的平均值。
我应该将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也无法正常工作。
解决该问题的一种方法是,只有在用户已经输入所有数据之后才初始化highlow。和init high = temp[0][0], low = temp[0][1]

关于c++ - 如何在C++中获得二维数组中一列的最低数目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62653027/

相关文章:

c++ - 将指向结构的指针转换为指向该结构的唯一成员的指针

c++ - 错误 C4018 与 vector 大小 () 在 c++

javascript - 如何在 Javascript 中将数组显示为视觉对象(例如迷宫)

arrays - Excel vba : Property let procedure not defined and property get procedure did not return an object

c - 使用数组将用户的输入存储到链表中

c++ - 由于 std::function 而导致构造函数重载的歧义

c++ - 允许非 const 在包装器模板中转换为 const

c++ - std::mutex 和 std::shared_mutex 的区别

c++ - 在 C++ 中管理内存所有权的最佳方式?共享指针或其他机制?

c++ - 将非 constexpr 标准库函数视为 constexpr 是否符合编译器扩展?