This is a program I made for an assignment thats supposed to find the min and max of 3 numbers. The program works when I run it this way but I'm having trouble following the logic of why.
#include <iostream>
using namespace std;
int main()
{
double num1 = 0, num2 = 0, num3 = 0, max = 0, min = 0;
cout << "CMPSC 201-Lab4 " << endl << "Find max and min among 3 numbers" << endl;
cout << "Please enter 3 numbers seperated by a space: ";
cin >> num1 >> num2 >> num3;
min = num1;
if (num2 < min)
{
min = num2;
}
else
{
min = num3;
}
max = num1;
if (num2 > max)
{
max = num2;
}
else
{
max = num3;
}
cout << endl;
cout << "The smallest number among (" << num1 << "," << num2 << "," << num3 << ",";//Outputs the numbers entered and displays min
cout << ") is " << min << endl;
cout << "The largest number among (" << num1 << "," << num2 << "," << num3 << ",";//Outputs the numbers entered and displays max
cout << ") is " << max << endl;
return 0;
Heres the code for the program. The way i thought about it was setting the first of the three numbers as the min, then using the if statements to change the min variable depending on the value of the other numbers. This works with any combination of 3 numbers in varying sequence.
A problem I see is that if the statement is true then the min WILL be number 2 because the first part of the if-else will execute.But say number 3 was smaller how would it become the min since that part of the if-else wont happen. This would make sense if the code was if-else if but it is not.
So am I not seeing something or does having it like this somehow make it an if- else if statement. Sorry if this is confusing im not sure how to word it any better.
Aucun commentaire:
Enregistrer un commentaire