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();
}
CodePudding user response:
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.
CodePudding user response:
The first conditions in all if
s 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 least8
. - Good if its
rating
is at least5
(and it's not Great). - Poor if its
rating
is at least1
(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");