c++short program problem

2007-12-19 8:23 pm
Give 4 potential problems of the following program when it is put into execution.

please go to here:
http://i4.photobucket.com/albums/y116/littley/p1.jpg

回答 (1)

2007-12-20 6:51 pm
✔ 最佳答案
This program accepts a file name from the command line (argv[1]), opens the file and read its contents. All numbers are then added and counted. When no more data is found, the average is calculated, but without checking to see if any valid input has been entered.

Here are my comments, added at the end of each line:

#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char**argv)
{
if(argc<=1) // print usage if filename not supplied
{
printf("Usage: average filename\n");
exit(0);
}
ifstream src(argv[1]);
int x;
long sum=0, count=0; // int could overflow, use long
while(src>>x)
{
sum+=x;
++count;
}
if(count>0)cout<<"average:"<<sum/count<<endl; // count could be zero
else printf("No input numbers found\n"); // message if no data found
cin>>x; // prevents execution screen from disappearing
return 0; // return required for integer function
}


收錄日期: 2021-04-13 14:45:20
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20071219000051KK00915

檢視 Wayback Machine 備份