Home > Software engineering >  Need help to correct my one way selection code
Need help to correct my one way selection code

Time:11-17

Why when i enter totalprice>50 (42 pens & above), it wont execute the if statement? Can someone help me? This is my code:

#include <iostream>
using  namespace std;

int main()
{
    int numbersOfPen;
    float totalPrice, total;
    cout<<"Enter numbers of pen:";
    cin>>numbersOfPen;
    totalPrice = 1.20 * numbersOfPen;
    
    if (totalPrice > 50)
    {
        totalPrice = totalPrice - (totalPrice * (30/100));
    }
    cout<<"Total price is RM"<<totalPrice;
     
    return 0;
}

CodePudding user response:

Adding a debug statement shows that the if statement is, indeed, executed. However, the 30/100, as @1201ProgramAlarm pointed out, evaluates to 0. In C , dividing two integers yields another integer, so 30/100 would round down to 0. That means nothing is subtracted so it seems like the if statement never runs. To fix this, rather than typing 30/100, just use a float literal: 0.3f. Putting it all together:

totalPrice = totalPrice - (totalPrice * 0.3f);

(As a side note, there is a shorthand way of typing the same statement as above using the -= operator)

totalPrice -= totalPrice * 0.3f;
  •  Tags:  
  • c
  • Related