0
votes

My Programme requests two variables: one integer and one float. Both must be greater than 0 and less than 2000. But testing an input of 45 and 0 it is accepting the value and showing the output of 0.00 although the conditions require (cash > 0) && (balance > 0).

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
    int cash;
    float balance ;
    cin >> cash >> balance;
    if((cash%5==0) && (cash <= balance) && (cash > 0) && (balance > 0) && (cash <= 2000) && (balance <= 2000))
    {
        balance = (balance - cash) - 0.50;
        cout << fixed;
        cout.precision(2);
        cout << balance;
    }
    else if (cash%5 != 0)
    {
        cout << fixed;
        cout.precision(2);
        cout << balance;
    }
    else if (cash > balance)
    {
        cout << fixed;
        cout.precision(2);
        cout << balance;
    }
    return 0;
}
1
your code does not enter the first if. it enters the last, i.e. else if (cash > balance). Was this not intented?default
Voting to close as why is this code not working. Please observe program state with printfs, and then generate a minimal example of the problem.Ciro Santilli 新疆再教育营六四事件法轮功郝海东

1 Answers

0
votes

Condition is false in expression (cash <= balance) , so it will not check other condition and jump to else part and cash > balance is satisfied so it will execute expression inside cash > balance part. For example

 int a=1,b=2,c=3;
 if((cout<<"first ") && ( a==2 ) && (cout<<" second\n"))
 {
    cout<<"condition true\n";
 }
 else
 {
    cout<<"condition false\n";
 }

Here first will print and when a==2 expression occur which is false so it will move to else part.