OR and less than operators not working as intended C language

二次信任 提交于 2020-01-16 17:35:34

问题


I'm doing an exercise of a book called programming in C language, trying to solve exercise 7.9 and so my code works perfectly until I add a conditional statement for the function to only accept variables greater than 0

I have tried changing it in many ways but nothing seems to work

// Program to find the least common multiple
#include <stdio.h>

int main(void)
{
 int lcm(int u, int v);

 printf("the least common multiple of 15 and 30 is: %i\n", lcm(15, 30));

 return 0;
 }
// Least common multiple
int lcm(int u, int v)
{
 int gcd(int u, int v);

 int result;

 if (v || u <= 0)
 {
    printf("Error the values of u and v must be greater than 0");
    return 0;
 }

 result = (u * v) / gcd(u, v);
 return result;
}
// Greatest common divisor function
int gcd(int u, int v)
{
 int temp;
 while (v != 0)
 {
    temp = u % v;
    u = v;
    v = temp;
 }
 return u;
 }

I expect the output of lcm(15, 30) to be 30, but I keep getting an error, if a delete de if statement inside the lcm function it works fine, but I want the program to return an error if for example I use (0, 30)


回答1:


if (v || u <= 0) is not saying "if v is less than or equal to zero OR if u is less than or equal to zero", like I believe you think it is. It's actually saying "if v is not zero, OR u is less than or equal to zero".

The operation a || b tests if a evaluates to non-zero, and if it doesn't, then it tests if b evaluates to non-zero. If either a or b is non-zero, then the expression is true.

In C, equality and relational operators like ==, !=, <, >, <= and >= produce the result 1 if the relation is true, and 0 if it is false, allowing you to use them in conditional expressions.

The correct conditional is:

if (v <= 0 || u <= 0)



回答2:


if (v || u <= 0) considers v as a boolean variable so it is true for every non zero value. So your if is true for any non zero v. Use if (v <= 0 || u <= 0)



来源:https://stackoverflow.com/questions/54373509/or-and-less-than-operators-not-working-as-intended-c-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!