Home > Software design >  i am currently making a subway fare calculator using C# Visual Studio, i need help assigning range t
i am currently making a subway fare calculator using C# Visual Studio, i need help assigning range t

Time:02-26

  int num2, fare;
        num2 = comboBox2.SelectedIndex;

        fare = num2   1;
        
        if (fare <= 6) { label4.Text = "15 Pesos"; }
        else if (fare <= 12 || fare >= 7) { label4.Text = "20 Pesos"; }
        else if (fare >= 13) { label4.Text = "30 Pesos"; }

here is my code,, i wanted to set a range for the fare so that when the program calculates, it corresponds to the assigned text.

basically if the answer is less than or equal to 6, the text will be "15 Pesos" and if the fare is less than 12 but greater than 7, the text will be "20 Pesos" and lastly if the fare is greater than or equal to 13, it will output "30 Pesos"

I ran my code but the second else if statement does not work and keep outputting "20 Pesos" even thought it should be "30 Pesos"

what should I do? Is my operators incorrect? pls help

btw Pesos is a currency in the PH

CodePudding user response:

You want && (and), not || (or). The else-if statement, as its written, says if it's less than or equal to 12 or greater than or equal to 7. So a large number, like 20, it's not less than or equal to 12, but it is greater than or equal to 7.

else if (fare <= 12 && fare >= 7) { label4.Text = "20 Pesos"; }

I'd recommend taking out the second condition. You've already confirmed it's greater than or equal to 7 when you checked that it's less than or equal to 6.

int num2, fare;
num2 = comboBox2.SelectedIndex;
    
fare = num2   1;
            
if (fare <= 6) { label4.Text = "15 Pesos"; }
else if (fare <= 12) { label4.Text = "20 Pesos"; }
else { label4.Text = "30 Pesos"; }

CodePudding user response:

In your second else if, the logic should be && (AND) not || (OR) because when you execute the if statements in an OR manner, any fare value that is 7 or above satisfies the condition. When you change it to a &&, you will be setting a range of values for the fare to fall in, which will allow it to break out of the second if statement and go to the third.

Happy coding, my friend!

  •  Tags:  
  • c#
  • Related