Defining Functions- c programming?

2016-10-04 11:55 am
Write the definition of a function isPositive, which receives an integer parameter and returns true if the parameter is positive, and false otherwise.

So if the parameter 's value is 7 or 803 or 141 the function returns true . But if the parameter 's value is -22 or -57, or 0, the function returns false .

My Code:

bool isPositive ( int x ) {
if ( x > 0 )
{
return true;
}
else {
return false ;
}
}

回答 (2)

2016-10-04 12:12 pm
✔ 最佳答案
That should work just fine. A shorter way to write it is to use the ?: conditional operator:

return x > 0 ? true : false;

An expression of the form A ? B : C will evaluate expression A. If it is nonzero ("true") then B will be the result and expression C will not be evaluated. Otherwise, C will be the result and expression B will not be evaluated.

Some programmers prefer to put the condition (the "A" part) in parentheses:

return (x > 0) ? true : false;

That helps if you're not used to C's operator precedence rules ("order of operations").

If you are using the bool, true and false definitions from <stdbool.h>, the code is even easier:

return x > 0;

The > operator returns an integer 0 (false) if the test fails or 1 (true) if the test succeeds. There's no need to do anything else with it. If you want to emphasize that the result is a bool value, then:

return (bool)(x > 0);
2016-10-04 3:51 pm
bool isPositive(int x){
return x>0;
}


your code can be better:

bool isPositive ( int x ) {
if ( x > 0 )
return true; // the else is not necessary since execution of the function stops at the return
return false;
}


收錄日期: 2021-05-01 21:11:10
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20161004035513AAcaxA7

檢視 Wayback Machine 備份