Operator '<' cannot be applied to operands of type 'decimal' and 'double'

后端 未结 3 673
攒了一身酷
攒了一身酷 2021-01-17 18:16

I\'m trying to come up with a program that calculates grades given from the users input. I am also trying to set a limit on how high or low the user input can be (i.e 0 <

相关标签:
3条回答
  • 2021-01-17 18:44

    As other's have already pointed out. In order to compare a decimal type using the greater than or less than operators you must compare it to another decimal type. In order to declare a literal number as a decimal it requires the M or m suffix. Here is the MSDN on the decimal type for reference.

    if (Exam_1 < 0.0m || Exam_1 > 100.0m)
    

    Here's a .NET fiddle with the fix.

    0 讨论(0)
  • 2021-01-17 18:48

    For decimal you have to add "M" suffix to the value to tell the computer it is a decimal. Otherwise computer will consider it as a double.

    yourDecimal < 98.56M;

    0 讨论(0)
  • 2021-01-17 18:50

    There are at least four issues I noticed in your code.

    Firstly, as mentioned, you should use M suffix to tell the C# compiler that it is a decimal for accepted comparison:

    if (Exam_1 < 0.0M | Exam_1 > 100.0M)
    

    But secondly, use || instead of |, because you want to do OR operation, not Bitwise-OR

    if (Exam_1 < 0.0M || Exam_1 > 100.0M) //change | to ||
    

    And thirdly, I think quite important for you to know this: you wouldn't need decimal data type for exam mark (unless your exam mark can be of format 99.12345678901234556789012345 - which is quite impossible).

    decimal is normally used for numbers requiring very high precision (such as money calculation in the bank) up to more than 16-digit accuracy. If your exam mark does not need that, don't use decimal, it is overkill. Just use double or int or float for your Exams and you are most probably in the right track.

    Fourthly, about your error handling, this is incorrect way of doing it:

    if (Exam_1 < 0.0 | Exam_1 > 100.0)
        Console.Write("Exam score cannot be less than 0. or greater than                      100.0. Please re-enter the score for Exam 1 <Example: 95.0>:");
        Exam_1 = Convert.ToDecimal(Console.ReadLine());
    

    due to two reasons:

    1. Your Exam_1 is outside of the block (there isn't {} bracket)
    2. You use if while you should use while

    This is the right way to do it:

    double Exam_1 = -1; //I use double to simplify
    
    Console.Write("Please enter score for Exam 1 <Example: 100.0>: ");
    Exam_1 = Convert.ToDouble(Console.ReadLine());
    
    while (Exam_1 < 0.0 || Exam_1 > 100.0) { //see the curly bracket
        Console.Write("Exam score cannot be less than 0. or greater than                      100.0. Please re-enter the score for Exam 1 <Example: 95.0>:");
        Exam_1 = Convert.ToDouble(Console.ReadLine());
    } //see the end curly bracket
    

    In C# language, indentation does not mean scoping, unlike in language like Python.

    0 讨论(0)
提交回复
热议问题