if statement - How to remove the error 'not all code paths return a value' in c# -
i error in c#: 'not code paths return value'. know main reason behind if
not followed else
. if not want compiler if condition inside if
not satisfied? example, in following program of trying find quotient without use of /
operator:
namespace consoleapplication1 { class program { public int quotient( int dividend, int divisor) { int i, quotient = 0, remainder; = divisor; while (i <= dividend) { += divisor; quotient++; remainder = dividend - i; if (i == dividend || ((i < dividend) && (remainder < divisor))) { return quotient; } } } static void main(string[] args) { program obj = new program(); console.writeline("enter first number:"); int = convert.toint32(console.readline()); console.writeline("enter second number:"); int b = convert.toint32(console.readline()); program obj = new program(); int quotient = obj.quotient(a, b); console.writeline("the quotient " + quotient); } } }
here want compiler return quotient
if condition (i == dividend || ((i < dividend) && (remainder < divisor)))
true. in case condition false, want flow go while (i <= dividend)
, increase i
, quotient
. compiler says 'not code paths return value'. how supposed rid of error? supposed give block of else
? also, there try-catch method overcome error?
the reason error because if code not go if (i == dividend || ((i < dividend) && (remainder < divisor)))
condition or fails function has nothing return - simplicity return 0
default:
public int quotient( int dividend, int divisor) { int i, quotient = 0, remainder; = divisor; while (i <= dividend) { += divisor; quotient++; remainder = dividend - i; if (i == dividend || ((i < dividend) && (remainder < divisor))) { return quotient; } } return 0; }
Comments
Post a Comment