【发布时间】:2016-04-06 08:44:58
【问题描述】:
我需要从文本文件中给出的数字列表中计算数字、平均值、总和、最高和最低的数量。我让它工作,但由于某种原因给了我文件中的数字列表,然后它说最高和最低 = 0 我无法找到帮助。
文件中的数字是
8 50 74 59 31 73 45 79 24 10 41 66 93 43 88 4 28 30 41 13 4 70 10 58 61
代码:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main ()
{
string STRING;
ifstream infile;
infile.open ("Numbers.txt");
while(!infile.eof()) // To get you all the lines.
{
getline(infile,STRING); // Saves the line in STRING.
cout<<STRING; // Prints our STRING.
}
int count = 0;
float sum = 0;
float num = 0;
float solution = 0;
infile.open("Numbers.txt");
if (infile)
infile>>num;
while (infile && count <25)
{
sum=sum+num;
count++;
infile>>num;
}
if (count <0)
{
solution=sum/count;
cout <<"Number of numbers is:"<<number<<endl;
cout<<"sum of all number is:"<<sum<<endl;
cout<<"The average of all numbers in the file is "
<<solution<<endl;
}
int highest;
int lowest;
while(infile >> highest)
highest = count;
while(infile >> lowest )
lowest = count;
cout<<" Highest is:"<<highest<<endl;
cout <<"Lowest is:"<<lowest<<endl;
infile.close();
}
【问题讨论】:
-
你有一个未声明的变量
number——我认为它应该是count。 -
if (count < 0)怎么可能是真的?count以0开头,然后您读取的每个数字都会增加它。 -
你不能再打电话给
infile.open(),除非你先打电话给infile.close()。但是你可以使用infile.rewind()。 -
你说你成功了。但是当我尝试你的程序时,它所做的只是打印出文件内容,并说最高和最低都是 0。它从不打印计数、总和或平均值,所以它从不将最后一个数字加两次。您确定您发布的代码是您描述的问题吗?
-
不要使用 !infile.eof()
标签: c++