运营商||不能应用于int和bool

时间:2016-12-09 12:40:07

标签: c#

class coding
{
    int a;
    public int setdata(int feet,int inches)
    {
        if (feet || inches < 0)
        {
            Console.WriteLine("invalid");

        }
        a = 12 * feet + inches;

        else { return a; }

    }
    public void display()
    {
        Console.WriteLine("the inches is" + a);
    }
}

我在这一行遇到了问题:

if (feet || inches < 0)

我不明白这个问题的原因。

6 个答案:

答案 0 :(得分:6)

If statement expects boolean expression so you need to write when the condition of your int value is invalid. You can redesign your code like this:

public int setdata(int feet,int inches)
{
    if(feet < 0 || inches < 0)
    {   
        return -1;
    }

     return 12 * feet + inches;
}

After that when you call setdata method

int result = setdata(feet, inches);
if(result == -1)
{
    Console.WriteLine($"Your input for inches:{inches} or feet:{feet} is invalid");
}

答案 1 :(得分:4)

this line :

if (feet || inches < 0)

is a very "natural language approach". It would be really nice if you could just code as you speak but the compiler language demands each case to be specified in detail.

On each side of the || operator the compiler expects a bool variable. So it is confused. You have to explicitly state each case:

if (feet < 0 || inches < 0)

the return result of this comparison (feet < 0) is of type bool

答案 2 :(得分:1)

Let's assume the numbers were different:

"I want to enter this if statement when feet has a value smaller than X, or inches has a value smaller than Y".

The if would then be:

if (feet < X || inches < Y)
{
    // condition met
}

The same syntax applies for all values of X and Y. Now, set X to 0 and Y to 0.

答案 3 :(得分:0)

For any Boolean expression, you have to write the expression twice;each time you make a decision explicitly so that the compiler knows exactly what to do:

if (feet < 0 || inches < 0)

Same goes with && :

if (feet < 0 && inches < 0)

答案 4 :(得分:0)

The || operator checks for atleast any one of the operands on either side of it is ture. Here you have two integers at both the sides of || operator which will throw an error. So it should be like

if(feet < 0 || inches < 0)

答案 5 :(得分:0)

Isn't it possible to set, say

 myData.setdata(3, -1);

which means "three feet without an inch"? If it's the case

public int setdata(int feet,int inches) {
  // compute length
  int value = 12 * feet + inches;

  // if the length is invalid, throw the exception
  if (value < 0) {
    if (feet < 0) 
      throw ArgumentOutOfRangeExample("feet");
    else    
      throw ArgumentOutOfRangeExample("inches");
  }

  a = value; 

  return value;
}

Or (if you don't want to have exceptions thrown)

public int setdata(int feet,int inches) {
  // compute length
  int value = 12 * feet + inches;

  // if the length is valid, assign it to a
  if (value >= 0) 
    a = value;
  else
    Console.WriteLine("invalid");

  return a;
}