Conditional statements in C# not working as I expected [duplicate] - c#

This question already has answers here:
Or in IF statement not working properly
(4 answers)
Closed 9 months ago.
I'm a beginner in c#, and I am currently practicing conditional statements and others. I wanted to create a simple movie rating code, where the user would enter a value and show the movie's rating.
I'm having a little trouble because I get the wrong rating when I type in a specific number.
A NY help with this code would be appreciated. Thank you.
static void Main(string[] args)
{
int rating;
string movie;
Console.Write("Enter the name of the movie: ");
movie = Console.ReadLine();
Console.Write("What is your rating: ");
rating = Convert.ToInt32(Console.ReadLine());
if (rating == 10 || rating >= 8)
Console.WriteLine("Great movie");
else if(rating <= 7 || rating >= 5)
Console.WriteLine("Good movie");
else if (rating <= 4 || rating >= 1)
Console.WriteLine("Poor movie");
else
Console.WriteLine("Very Very Poor");
Console.WriteLine("The movie {0} is of {1} rating", movie, rating);
Console.ReadKey();
}

Looking at the conditional statements, let's think about what would happen if I were to enter, say, 4 for the rating:
if (rating == 10 || rating >= 8)
4 is not 10, and it's not >= 8. Moving on...
else if(rating <= 7 || rating >= 5)
4 is not >= 5, but it IS <= 7. Since this is an || condition, the result is true if either side is true, and that is the case here. I don't think that's what you intended.
You probably want && for these, instead of ||. Additionally, since we go in order from large to small, using else if blocks, you only need to check the lower bound of each rating.
As this is beginning work, I'll leave incorporating these suggestions into the original code for the OP.

The first conditions in all ifs are useless: rating == 10 || rating >= 8 - when rating >= 8 we have no need to check rating == 10; rating <= 7 || rating >= 5 meets every rating - all integer numbers either less than 7 or greater than 5 etc.
Film is
Great if its rating is at least 8.
Good if its rating is at least 5 (and it's not Great).
Poor if its rating is at least 1 (and it's not Good).
Very Very Poor in other cases.
if (rating >= 8)
Console.WriteLine("Great movie");
else if (rating >= 5)
Console.WriteLine("Good movie");
else if (rating >= 1)
Console.WriteLine("Poor movie");
else
Console.WriteLine("Very Very Poor");

Related

Do-while loop won't stop after the while part gets false C# [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This is a part of a code which determines whether a number is prime or not. I know it could be solved in other ways, but I cant figure out why this loop wont stop if I put in a "5" as a number. The divisor reaches 5 after the third "divisor++;" (the divisor starts from 2) but the while loop wont quit.
Can anyone help me?
do
{
if (number % divisor == 0)
{
Console.WriteLine("Number is not a prime.");
}
if (divisor == number - 1)
{
Console.WriteLine("Number is prime.");
}
divisor++;
} while (number % (divisor -1) != 0 || divisor != number);
The condition should probably be ... != 0 && divisor != number.
Difference being && rather than ||.
while (number % (divisor -1) != 0 || divisor != number)
Above statement would never let it break.
For example if divisor is 5 then
5 % (5-1) would 1 and loop will continue
when divisor is 6 then
6 != 5 and it will continue
you should use
while (number % (divisor) != 0);

Making an int be multiple values?

Is there any way to have a int value that is multiple values?
Under here you can see the code, im doing a minigame as a proof of concept.
currently i have x happen at loop number 4 and y happens at loop number 9.
Is there any way to repeat theese actions on other loops wihout maing it a huge mess like this: i == 4||i == 14 || i == 18
what im trying to ask is if its possible to just write i == a
and then have a be multiple values.
If you havent figured already, im quite the beginner at C#, so if you can explain it in a easy to understand way, i would be very thankfull.
If what i wrote is a bit hard to understand, then im sorry for not being a native english speaker, just ask if you're unsure of what i mean.
for (int i = 0; i < 50; i++)
{
string input;
input = Console.ReadKey().Key.ToString();
Console.Clear();
if (input == "A") Animation.frame1();
else Animation.fall();
if (i == 4) Animation.blocklow2();
if (i == 9) Animation.blockhigh2();
input = Console.ReadKey().Key.ToString();
Console.Clear();
if (input == "W" && i == 4) Animation.blockjump();
if (input == "S" && i == 9) Animation.blockduck();
if (input == "D" && i != 4 && i != 9) Animation.frame2();
else if (input != "W" && i == 4) Animation.fall();
else if (input != "S" && i == 9) Animation.smack();
if (i == 3) Animation.blocklow();
if (i == 8) Animation.blockhigh();
}
You could do if (new int[] { 4, 14, 18 }.Contains(i)) to check for multiple values.
Store a list of ints that you want to check against and then use .Contains
List<int> frame2ints = new List<int>{4,9};
if (input == "D" && !frame2ints.Contains(i)) Animation.frame2();
In certain situations you can perform bitwise tests to see whether some bits are set in your number:
if ((x & 4) != 0)
{
// This case covers numbers
// 4, 5, 6, 7, 12, 13, 14, and many others...
}
General answer to your question is NO, and it only makes sense to use additional knowledge about the values you are testing and then use that knowledge.
Another option is to test whether a number belongs to a sequence, like HHLV said in other answer.
So, how did you get to values 4, 14 and 18?

Easier way to 'or' operators in if statements (C#)

I'm making a game in unity, and I have this 'if statement' that by every 5 waves my shop menu will become visible. The code does work, but I am certain I'm doing something wrong or could do something better!
if (waveCount == 5 || waveCount == 10 || waveCount == 15 || waveCount == 20 || waveCount == 25 || waveCount == 30 || waveCount == 35 || waveCount == 40 || waveCount == 45 || waveCount == 50)
{
// yield return new WaitForSeconds(shopWait);
shopPanel.SetActive(true);
}
As you can see the 'if statement' not that good, normally it continues all the way to waveCount == 100 but i cut that out. There must be a simpler or cleaner way to do this :/ but i just can't wrap my head around it :(
Edit 1:
Thanks, I didn't know much about modulo, know I know what I have to read about :)
You can use modulo operation:
if (waveCount % 5 == 0)
Yes, there are indeed simpler ways of doing this. If you use a little bit of maths and logic, you can figure this out.
Since you want to check whether the value of waveCount is a multiple of 5, you can use % to get the reminder of waveCount / 5. If that reminder is 0, waveCount is a multiple of 5.
if (waveCount % 5 == 0 && waveCount <= 100)
I added waveCount <= 100 to replicate your code's behaviour when waveCount is larger than 100 i.e. not get into the if statement.
Alternatively, you can put all the values into a list:
var list = new List<int>();
for (int i = 1 ; i <= 20 ; i++) {
list.Add(i * 5);
}
And then check whether the list contains the number:
if (list.Contains(waveNumber))
The advantage of this is that if you decided to change how the game works and say that the shop menu can be opened at waves 9, 52, and 77, you just add the numbers to the list, without modifying the if statement. This provides a lot of flexibility.
if (waveCount % 5 == 0 && waveCount <= 50) {
//...code
}
If your “if” statement's body just contains shopPanel.SetActive(true); you can do that without even using “if” like that.
shopPanel.SetActive(waveCount % 5 == 0 && waveCount <= 50);
Give it a try
if (waveCount % 5 == 0 && waveCount <= 50)
Use the modulo-operator:
if(waveCount % 5 == 0 && waveCount <= 100) ...
The operator calculates the remainder of an integer-divison. In your case the statement should return zero indicating that your number divided by 5 has no remainder.
Just to generalize: in case the data you have doesn't match a pattern, you can put all the things to match against in a set, then test the set for membership:
var thingsToMatch = Set(2, 5, 8, 14, 23, 80, 274...);
if (someNumber in thingsToMatch) {...}
As long as you know the set isn't being recreated everytime the function is called, this has proven to be fairly fast. If your language doesn't automatically cache the set, you can make it a static variable of the function.
You can use the remainder operator for this:
if (waveCount % 5 == 0 && waveCount > 0 && waveCount <= 50)
{
//yield return new WaitForSeconds(shopWait);
shopPanel.SetActive(true);
}
You can test whether the remainder of the division by 5 is 0, which means that the number is divisible by 5.
if (waveCount % 5 == 0 && waveCount >= 5 && waveCount <= 50)
C# performs integer math on integer number types (int, long, uint, ...).
Example:
13 / 5 = 2
I.e. you never get a decimal fraction part. The complementary operation is the modulo operation. It gives you the remainder of this division:
13 % 5 = 3
I.e., 13 / 5 is 2 plus remainder 3. Together, division and modulo operation allow you to perform the reverse operation.
(5 * (13 / 5)) + (13 % 5) =
(5 * 2 ) + ( 3 ) = 13
If you have irregular figures, quite different approaches are to use a switch statement:
switch (waveCount) {
case 5:
case 10:
case 15:
case 20:
case 25:
case 30:
case 35:
case 40:
case 45:
case 50:
shopPanel.SetActive(true);
break;
}
or an array of allowed values:
private static readonly int[] AllowedValues =
new int[] { 5, 10, 15, 20, 25, 30, 35, 40, 45, 50 };
if(Array.IndexOf(AllowedValues, waveCount) >= 0) { ... }

return a % in C# with if statements

I am working on a school project and I am trying to write a C# program that will allow the user to input total sales. I need to take the total sales and calculate it by the profitRatio as follows:
totalSales profitRatio
0-$1,000: 3%
$1,000.01-%5,000 3.5%
$5,000.01-$10,000 4%
Over 10,000 4.5%
The next step would be to calculate the total sales by the % category that it matches and store that data. I will also want to display the profit ratio % used to the user along with the new profit. Will “if then” statements work to do this if written like this?
private decimal ReturnRatio()
{
if (totalSales > 0 && totalSales < 1000)
{
profitRatio = .03M;
}
else if (totalSales >= 1000.01 && totalSales < 5000)
{
profitRatio = .035M;
}
else if (totalSales >= 5000.01 && totalSales <= 10000)
{
profitRatio = .40M;
}
else if (totalSales < 10000)
{
profitRatio = .045M;
}
}
In your last branch, else if (totalSales < 10000) you would allow in numbers that are <= 0>. I think that last branch should be else if (totalSales > 10000).
Well, the last branch should probably really be an else statement that handles other amounts since the user is allowed to enter amounts. For example:
else if (totalSales > 10000)
{
profitRatio = .045M;
}
else
{
Console.WriteLine("You entered an invalid amount.");
}
If then statements will work, but if I were your teacher I would be hoping for more. You should consider creating a Range class with a field for Min and a field for Max, then create objects to represent each category.
Place these Range objects in a collection like a List, then do a foreach loop to go through each Range object individually.
If this were code in an enterprise system, I would hunt you down unless this was the hot loop in some extreme performance stuff.

How to condense my if statement [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have been asked to create a mark to grade converter in Windows Form Application.
My code below is from the click of a button. Once a user has input their mark into 'Markbox' and the button is clicked the if statement will run and it will find the correct range of the mark. Then it will display a grade, relevant to the mark in 'Gradelb'.
Below is the code under the button click command. I wanted to condense it down to reduce code line space as well as making it more manageable.
void SubmitBtn_Click(object sender, EventArgs e)
{
int mark = int.Parse(Markbox.Text);
if (mark >= 45 && mark <= 50) Gradelb.Text = "A*";
else if (mark >= 40 && mark < 45) Gradelb.Text = "A";
else if (mark >= 35 && mark < 40) Gradelb.Text = "B";
else if (mark >= 30 && mark < 35) Gradelb.Text = "C";
else if (mark >= 25 && mark < 30) Gradelb.Text = "D";
else if (mark >= 20 && mark < 25) Gradelb.Text = "E";
else if (mark >= 0 && mark < 20) Gradelb.Text = "U";
else MessageBox.Show("Please enter a mark between 0-50");
Apologies for any errors or incorrect terminology, I am a new Apprentice employee.
string Gr = new string[] { "A*", "A", "B", "C", "D", "E", "U" };
if(mark >=0 && mark <= 50)
Gradelb.Text = Gr[10 - Math.Max(4, (int)Math.Ceiling(mark/5f))];
else
MessageBox.Show("Please enter a mark between 0-100");
A word of caution: After living a decade of "one-liner"'s life, I can advise you one thing: There is no guarantee that this code will be any more efficient than yours.
Explanation
Since the grades and the marks range they are linked with follow a fixed pattern, I created an array of grades so that I could refer to each grade by array index. Now all I need is a expression that could convert a given number to index.
46-50 => 0
40-45 => 1
and so on...
This can be done by dividing the number by 5 (since that is the group size in your example). So for example dividing 41 by 5 will give you 8.2. Doing a Ceiling() (which returns nearest greater or equal integer) on it will give 9. Subtracting this value from 10 will give you the index of second group (which is grade A).
Math.Max() (which returns larger of the two parameters) is simply there to ensure that values which are out of array bounds do not cause an exception. This will be the case when marks are 15 or less.

Categories