See the below photo for reference:
I have a problem in finding the min and max number in .txt file.
The number is stored in a file as one number per line. The Programm should go through these numbers and find the biggest and smallest number.
Update: I solve this problem, but I face another issue due to the type of numbers.
Let say I have the following numbers:
0005.00
0005.23
52340.53
0000.01
0111.10
0001.00
2523.00
How can I get the right answers?
#include<fstream>
#include<cstdlib>
#include<iostream>
#include <iomanip>
using namespace std;
int main()
{
int counter=0, number;
float sum = 0, average=0;
char file_name [20];
cout << "enter filename: ";
cin >> file_name;
ifstream input;
input.open(file_name);
if (! input)
{
cout << "Can't open file" << file_name;
//exit (0);
}
input >> number;
float min = number;
float max = number;
while (input>>number)
{
counter++;
sum=sum+number;
// Now, we can also check for Min/Max...
if (number > max) max = number;
if (number < min) min = number;
}
average=sum/counter;
cout<< fixed<<cout.precision(3);
cout<< "The average file in file test is was "<<average<<endl;
cout<< fixed<<cout.precision(3);
cout<<"The largest number is: "<<max<<endl;
cout<< fixed<<cout.precision(3);
cout<<"The smallest number is: "<<min<<endl;
input.close();
return 0;
}
When i run it, the min and max values are zero! Any help is appreciated.
Your first while loop will read to the end of file; thus, your second while loop won't actually read anything - you will already be at the file's end before it starts.
You should incorporate the code that is the 'body' of the second loop into the first one, and remove that 'redundant' second loop. You are also assigning the Min and Max variables the wrong way round:
while (input>>number)
{
counter++;
sum=sum+number;
// Now, we can also check for Min/Max...
if (number > Max)
Max = number;
if (number < Min)
Min = number;
}
average = sum / counter;
You should also give your Min and Max better initial values (unless you know there will be both positive and negative numbers in the data):
float number, sum = 0, average, Max = -FLT_MAX, Min = FLT_MAX;
Feel free to ask for further clarification and/or explanation.
This loop reads all numbers in the file:
while (input>>number)
{
counter++;
sum=sum+number;
}
After that loop, input is already at the end of the file and the next loop will not read any numbers.
Read the numbers once and do all processing in a single loop. Alternatively, store the numbers in a std::vector and then work on that.
Moreoever, you never modify Min and Max in your code. What this loop:
while (input>>number)
{
if (number>Max)
number=Max;
else
number=Min;
}
does instead is to clip the numbers such that any number bigger than 0 (Max) is set to 0 and any other number is set to 0 (Min).
You probably want something along the line of
double number;
input >> number;
double min = number;
double max = number;
while ( input >> number) {
if (number > max) max = number;
if (number < min) min = number;
}
I used the first number to initialize min and max. If you don't to that, 0 is no good initial value for min and max, but you can use std::numerical_limits<double>::min as initial value for max and std::numerial_limits<double>::max as initial value for min.
Related
I'm trying to find the highest value in a given list, but in an input list like this
7 385 -390 305 470 -145 255 30
my output is wrong, 385 instead of 470.
Could anyone please guide me towards my error!
Task description:
Read in an input value for variable numIn. Then, read numIn integers from input and output the largest of the integers read. End with a newline.
Ex: If the input is 2 345 -5, then the output is:
345
my code below
#include <iostream>
using namespace std;
int main() {
int numIn;
int high = 0;
cin >> numIn;
for (int i = 0; i < numIn; i++) {
cin >> numIn;
if (numIn > high) {
high = numIn;
}
}
cout << high << endl;
return 0;
}
First of all, your list has negative numbers. You can't set the default value of high to 0 since a list with all negative numbers won't work if you do this.
The error in your loop occurs because you overwrite numIn. Use a different variable for the number of input numbers.
cin >> numIn; // numIn is the number of input numbers
for (int i = 0; i < numIn; i++) {
cin >> numIn; // oops, numIn is now the first input number. it has been overwritten.
if (numIn > high) {
high = numIn;
}
}
A correct solution would look like this:
#include <iostream>
int main() {
int N; // assume that N >= 1. You could also replace this with numIn.
std::cin >> N;
int max;
std::cin >> max; // take in the first integer outside the loop
for (auto i = 1; i < N; i++) { // loop which runs N - 1 times
int E;
std::cin >> E;
max = std::max(max, E);
}
std::cout << max << '\n';
}
Without using std::max()
If you don't want to use std::max(), replace the line where you use it with a normal comparison (this is what std::max() does internally too)
if (E > max) { max = E; }
The program objective:
Write a program which allows a teacher to determine the min, max, and average grade from grades entered. The teacher will continuously enter grades until the sentinel is specified. For this example, a grade of -1 will be used to denote grading is completed. The min, max, and average grade should then be displayed to the teacher. This program should not accept invalid grades to be used [0, 100].
I have attached a picture of my code, please have a look. When I run it, it shows me that there is an error.
Let's start at the bottom and work our way up.
Reading numbers
int number = 0;
while (std::cin >> number)
{
if (number == -1) break;
}
Running Sum
The sum is the addition of every number; no need to store numbers in a container.
int number = 0;
int sum = 0;
while (std::cin >> number)
{
if (number == -1) break;
sum += number;
}
Running Maximum
This one is a little bit tricky. The maximum wants to be the first value entered.
int number = 0;
int sum = 0;
int maximum = 0; // All variables should be initialized.
std::cin >> maximum;
sum = maximum;
if (maximum == -1)
{
return 0;
}
while (std::cin >> number)
{
if (number == -1) break;
sum += number;
if (number > maximum)
{
maximum = number;
}
}
The calculation of the minimum and average is left as an exercise for the OP (You need to do some work on your own).
Hint: Average is the sum divided by the quantity of numbers entered. Be aware that the average needs at least 1 value so that there is no division by zero (usually 3 values are used for an average). Again, no container necessary for this either.
I posted this answer without looking at the OP's code since the OP originally posted a link to an image and firewalls are blocking the link.
I'm writing a program that prompts the user to enter integer numbers.
The program stops reading when user inputs 0.
It should output the max and min element among inputed numbers.
I must write it without using arrays.
Input: 1 2 3 4 5 0
Output: min=1 max=5
My code:
#include <iostream>
using namespace std;
int main()
{
int n,max,min;
min=0;
max=0;
do{
cin>>n;
if(n>max){
max=n;
}
if(n<min){
min=n;
}
}
while(n!=0);
cout<<max<<endl;
cout<<min;
}
The problem is that when I enter the integers from my example the output is min=0 max=5, instead of min=1 max=5.
How can I fix it?
You may want to input a starting value first, then loop:
int main()
{
int n, min, max;
cin >> n;
min = n;
max = n;
if (n != 0)
{
while (cin >> n)
{
if (n == 0) break;
if (n > max) max = n;
if (n < min) min = n;
}
}
std::cout << "min: " << min << ", max: " << max << "\n";
return 0;
}
In the code above, the first value is read and checked for 0. The program stops input if the value is zero.
The minimum and maximum are assigned the first value.
Then the loop starts.
I used Dev c++ 5.5.3 to write some programs. one of the programs is about getting some numbers (integer) until zero and then prints max, min , avg. In my computer everything is fine. in someone else computer, it does not show the right average and it shows very strange numbers 4.612521 e+8 and like this. I define a variable avg and calculate the value and then print it. The other one calculate the average directly when calling cout. can someone check This programs:
Program 1 which doesn't show the right answer:
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int n;
int max , min , count = 0 , s;
float avg;
cout<<"This program gets some numbers until zero and then prints maximum, minimum and average of them"<<endl<<"Please enter a number : ";
cin>> n;
max = n;
min = n;
while (n!= 0)
{
count ++;
s+=n;
if (n>max)
{
max = n;
}
if (n<min)
{
min = n;
}
cout<< "Please enter a number : ";
cin>>n;
}
cout<<"ZERO DETECTED!\n\n"<<endl;
cout<<"Maximum: "<<max<<endl;
cout<<"Minimum: "<<min<<endl;
avg = (float) s/count ;
cout<<"Average: "<<avg<<endl; // NOTE NOTE NOTE NOTE
return 0;
}
Program 2 which shows the right answer:
#include <iostream>
using namespace std;
int main(int argc, char** argv) {
int n;
int max , min , count = 0 , s;
float avg;
cout<<"This program gets some numbers until zero and then prints maximum, minimum and average of them"<<endl<<"Please enter a number : ";
cin>> n;
max = n;
min = n;
while (n!= 0)
{
count ++;
s+=n;
if (n>max)
{
max = n;
}
if (n<min)
{
min = n;
}
cout<< "Please enter a number : ";
cin>>n;
}
cout<<"ZERO DETECTED!\n\n"<<endl;
cout<<"Maximum: "<<max<<endl;
cout<<"Minimum: "<<min<<endl;
//avg = (float) s/count ;
cout<<"Average: "<<(float) s/count<<endl; //NOTE NOTE NOTE NOTE
return 0;
}
Both programs have undefined behaviour because s is not initialised and has not been assigned a value before you try to read from it for the first time:
int max , min , count = 0 , s;
[...]
s+=n;
All behaviour you have seen and the fact that it apparently "worked" on your computer and did "not work" on someone else's were more or less random occurrences.
Here's an easy fix:
int max , min , count = 0 , s = 0;
Note that your compiler should have warned you about the uninitialized variable. If not, then perhaps you should choose a higher warning level.
Also note that there are a lot of other flaws in your program, for example the use of using namespace std, that you declare multiple variables on the same line or that some of your variable names are not very descriptive.
The directions are: Design and code a program that asks the user how many numbers from which to determine an average. Then prompt the user for the integer values and sum them to a total. Display the sum of the numbers and the calculated average with appropriate accompanying text. The average should be shown with 1 decimal place. Repeat the process until the user enters zero (0) as the number of values to be averaged. You may use either a "while" loop or a "do…while" loop for the main program loop.
Use one function to read and sum the values and another function to display the sum and average. Use a "for" loop to read and sum the values.
The for loop doesn't seem to be executing, but I can't figure out why.
#include <cstdlib>
#include <iostream>
#include <iomanip>
using namespace std;
int sumNums(int amount, int, int, int);
void displaySum(int sum, int avg);
main()
{
int amount = 0;
cout <<"How many numbers do you wish to average? ";
cin >> amount;
int avg = 0, sum = 0;
while (amount != 0)
{
for (int lim = 0; lim == amount; lim++)
{
int number = 0;
cout <<"Enter a value"<< endl;
cin >> number;
sumNums(amount, number, sum, avg);
displaySum (sum, avg);
}
}
}
int sumNums (int amount, int number, int sum, int avg)
{
sum = sum + number;
avg = sum / amount;
return sum, avg;
}
void displaySum (int sum, int avg)
{
cout <<"The sum is "<< sum <<" and the average is "<< avg << endl;
}
for (int lim = 0; lim == amount; lim++)
Here you set lim to 0 and the code runs only if amount is not 0. In your for you execute only if lim equals amount which never happens.
Whatever your condition is, it must evaluate to true for every iteration that you want to do.
Most probably, you will want to execute until lim equals amount so that means that you want it to execute for every iteration where lim is lower than amount.
for(int lim = 0; i < amount; lim++)
for (int lim = 0; lim == amount; lim++) // so wrong...
change to
for (int lim = 0; lim < amount; lim++)