Reputation: 27
can someone explain how the highest and lowest works in the if statement? and what happen when we use cin.sync()? it works but i dont know how it works.
using namespace std;
int main()
{
string name, p1, p2;
int n;
double salary, sales, income, commission, highest, lowest;
highest=0;
lowest=9999999;
for(n=1; n<=2; n++)
{
cout<<"Enter your name?"<<endl;
getline(cin,name);
cout<<"Enter "<<name<<" salary:"<<endl;
cin>>salary;
cout<<"Enter "<<name<<" total price of car sold"<<endl;
cin>>sales;
cin.sync();
commission=sales*0.03;
income=commission+salary;
cout<<name<<" income is RM"<<income<<endl;
if(income>highest){
highest=income;
p1=name;
}
if(income< lowest){
lowest=income;
p2=name;
}
}
cout<<"Highest income is salesman named "<<p1<<endl;
cout<<"Lowest income is salesman named "<<p2<<endl;
}```
Upvotes: -1
Views: 46
Reputation: 56
This loop will run only two times. Once for n=1, and then for n=2.
From what I understand we want to get the highest value. So we initialize it with the min value that is 0. Next whatever value salary has for the first time will be set as highest. After this (from the second time) only the value of the highest will change only if(income>highest). The var highest will store the max value.
Similarly, it works for the lowest. We initialize the lowest with a very high value so that any first value would lower than it.
Upvotes: 1