【发布时间】:2021-07-06 15:55:52
【问题描述】:
我有一个包含行和列的文件
2456 128 234 67
2368 200 249 70
2655 212 250 89
我需要找到每列的平均值。这是我尝试的:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string input;
ifstream namefile("payment.txt");
if (!namefile)
return (cout << " ERROR : cannot open file.\n"), 1;
while (getline(namefile, input))
cout << input << endl;
namefile.clear();
namefile.seekg(0);
int a {}, b {}, c {}, d {};
namefile >> a >> b >> c >> d >> e;
int price1 = a;
int price2 = b;
int price3 = c;
int price4 = d;
for (a = 0; a < 3 ; a++)
{
int total = a ;
a++;
price1 = a/3;
}
std::cout << "The average price for A is " << price1 << '\n';
for (b = 0; b < 3 ; b++)
{
int total = b ;
b++;
price2 = b/3;
}
std::cout << "The average price for B is " << price2 << '\n';
}
我尝试运行此编码,但它不起作用。有谁知道如何使它工作?请帮帮我
【问题讨论】:
-
“没用”是什么意思?
-
这段代码有太多错误。我希望看到
namefile >> a >> b >> c >> d >> e;在一个循环中,但你只调用它一次。此外,还不清楚a上的循环应该如何计算文件中条目的平均值。循环从a=0开始做一些事情,循环之后price1始终是2/3,即0。不要试图一次编写所有代码。例如,您可以尝试编写计算某些硬编码数字的平均值的代码。一旦你做对了,你可以添加更多 -
旁注:当您有顺序命名或编号的变量时,通常使用数组的代码会更简单。