Hi. I'm completely new to programming and I have a question about a program I have to write.
I need to read some numbers from a file and display the sum of the numbers > 0, count of the numbers > 0, sum of the number < 0, count of the numbers < 0, and a count of the numbers == 0.
I'm completely stuck on how I should write the while loops. Hell, how I should write anything. I think I may have the beginning correct. This is my measly attempt:
I'm thinking that te first number read in with the infile, was a 6. So, since value never decreases and become less than 0, you enter an endless loop, always displaying the first number, which was a 6;
Yep, that's what I ended up doing. Would I nest the other if statements inside? To add the counts for each if statement, do I add count++ inside each one?
If it helps, the numbers in my file are -9, 6, 0, and 4.
You seem to be referring to your original post code, as there is no count, or other if statement, in it. Seems the above program was just a test to get things figured out..
#include <iostream>
#include <fstream>
usingnamespace std;
int main()
{
ifstream inFile;
int value;
int sum = 0; // Initialize to 0;
int count = 0;// same as above
inFile.open("My_Path.txt");
while(inFile >> value) // While file can be read in ( You can increase numbers in text
{
count++; // Increase count
cout << "Sum of #'s > " << count; // Print out variable
sum += value; // Increase sum total
}
inFile.close(); // Close file.
cout << "Sum total of all " << count << " numbers, was "<< sum << endl;
// Print out the results
return 0;
}
If it helps, the numbers in my file are -9, 6, 0, and 4.
Yep. First number that was greater than 0 is the 6. Line 19 disregarded the -9, since it was not greater than 0
My first post was me completely lost with what to do. I then thought I had to nest while loops.
1 2 3 4 5 6
while(inFile >> value) // While file can be read in ( You can increase numbers in text
{
count++; // Increase count
cout << "Sum of #'s > " << count; // Print out variable
sum += value; // Increase sum total
}
This is what I'm stuck on. How do I get the multiple values read and display each count and sum for >, <, and then display the count for == 0.
You need to have 3 sum variables and 3 count variables and test as each new number is read in:
1. setup variables count_of_negative_numbers, sum_of_ngative numbers, count_of_positive_numbers etc etc
2. read a new number called new_number
3. if new_number < 0
then increment count-of_negative_numbers and add new_number to sum_of_negative numbers
4. if new_number == 0 ... same process
5. do the same for new_number > 0 ...
...