Help with a C++ code! It's just not working properly!!

Discussion in 'C++' started by karonu, Apr 30, 2008.

  1. karonu

    karonu New Member

    Joined:
    Apr 30, 2008
    Messages:
    1
    Likes Received:
    0
    Trophy Points:
    0
    Hi, i have to write a program that will search a file of numbers of type double and write the largest and the smallest numbers to the screen. The program should also output the average of the numbers in the file to the screen. The file contains nothing but numbers of type int separated by blanks or line breaks.

    This is my code! I created a file containing only 7 numbers from 1-7. When I run the program the 7 shows as the highest number but 3 shows as the lowest number??? and the average as -9.3!!!! I can't figure what's wrong with it! can someone please help me?

    Code:
    #include <fstream>
    #include <iostream>
    
    #include <cstdlib>
    using namespace std;
    int main()
    
    {
    ifstream in_stream;
    
    double  min, max=0;
    double number=0;
    double  sum=0, count=0, average;
    
    in_stream.open("D:\numbers.txt");
    
    
    in_stream >> min;
    in_stream >> max;
    
    
    while (number != 0)
    
    {
        in_stream >> number;    
    	sum += number;
        count ++;
    
    }
    if (count > 0)
    
    average = sum/count;
    
    if (in_stream >> number)
    {
    
    	min = max = number;
    
    	while (in_stream >> number)
    	{
    		if(number< min)
    		{
    			min = number;
    		}
    
    		if (number> max)
    		{
    			max = number;
    		}
    	}
    
    	in_stream.close();
    
    
    cout << "The largest value in the file is " << max << "\n";
    cout << "and the smallest value in the file is " << min << "\n";
    cout <<  "Average is  "<< average << endl;
    cout << "\n";
    }
    
    return 0;
    }
     
    Last edited by a moderator: May 1, 2008
  2. shabbir

    shabbir Administrator Staff Member

    Joined:
    Jul 12, 2004
    Messages:
    15,376
    Likes Received:
    388
    Trophy Points:
    83
    Moved to C-C++ forum
     

Share This Page

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice