【发布时间】:2020-06-28 04:22:40
【问题描述】:
所以我试图从文件中读取一个二维数组,找到该数组中的最小数字,然后从数组中的每个元素中减去该数字。
我的文件“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;
}
【问题讨论】:
-
numbers[i][j] - lowest不做任何事。但这不是你的问题。我怀疑您发布的代码不是您正在运行的代码,您可能在某处有一个额外的j++。 -
@paxdiablo 是对的。
numbers[i][j] - lowest不做任何事情。它评估并丢弃结果。您需要评估和存储。我认为您也可以同时评估和打印。 HTH