从2D数组中减去min

时间:2020-03-17 04:52:21

标签: c++ arrays file

所以我试图从文件中读取2D数组,找到该数组中最小的数字,然后从数组中的每个元素中减去该数字。 我的文件“ ola4.dat”包含: 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 我制作了文件,因此很容易发现它正在工作,因为它应该打印0和全1。由于某种原因,我的输出是: 1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 谁能告诉我我要去哪里错了?

谢谢

#include <iostream>
#include <iomanip> 
#include <fstream>

using namespace std; 

int main ()
{

   int numbers[5][10]; //array
   int count 0; 
   ifstream myIn; //file name for ola4.dat
   int lowest; 

   myIn.open("ola4.dat"); 

//loop to read in 2D array
   for(int i = 0; i < 5; i++){
      for(int j = 0; j < 10; j++){

           myIn >> numbers[i][j]; 
         }
    }

    lowest = numbers[0][0]; //setting lowest to first element in array 

//loop to find lowest 
    for (int i = 0; i <5; i++){

       for (int j = 0; j < 10; j++){

           if(numbers[i][j] < lowest)
            lowest = numbers[i][j]; 
          }
     }

//loop to subtract lowest from each element in the array
    for (int i = 0; i <5; i++){

        for (int j = 0; j < 10; j++){

           numbers[i][j] - lowest; 
          }
     }

//loop to print each element in the array
    for (int i = 0; i <5; i++){

       for (int j = 0; j <10; j++){

           cout << numbers[i][j] <<' '; 
          }
       cout << endl; 
    } 

2 个答案:

答案 0 :(得分:1)

numbers[i][j] - lowest; 

不做您想做的事。它只是评估该术语并将其丢弃。

您需要

numbers[i][j] -= lowest; 

numbers[i][j] = numbers[i][j] - lowest; 

我建议使用第一种形式。它更简单,更不易出错。


我不清楚我为什么在输出中每行只能得到5个数字。您应该每行获得10个数字。

答案 1 :(得分:0)

在下面尝试一下:

#include <iostream>
#include <iomanip> 
#include <fstream>

using namespace std; 

int main ()
{

   int numbers[5][10]; //array
   int count 0; 
   ifstream myIn; //file name for ola4.dat
   int lowest; 

   myIn.open("ola4.dat"); 

//loop to read in 2D array
   for(int i = 0; i < 5; i++){
      for(int j = 0; j < 10; j++){

           myIn >> numbers[i][j]; 
         }
    }

    lowest = numbers[0][0]; //setting lowest to first element in array 

//loop to find lowest 
    for (int i = 0; i <5; i++){

       for (int j = 0; j < 10; j++){

           if(numbers[i][j] < lowest)
            lowest = numbers[i][j]; 
          }
     }

//loop to subtract lowest from each element in array
    for (int i = 0; i <5; i++){

        for (int j = 0; j < 10; j++){

           numbers[i][j] -= lowest; 
          }
     }

//loop to print each element in array
    for (int i = 0; i <5; i++){

       for (int j = 0; j <10; j++){

           cout << numbers[i][j] <<' '; 
          }
       cout << endl; 
    } 
相关问题