OR,并且少于不按预期的C语言运行的运算符 [英] OR and less than operators not working as intended C language

查看:70
本文介绍了OR,并且少于不按预期的C语言运行的运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在练习一本名为《用C语言编程》的书,试图解决练习7.9,因此我的代码运行良好,直到为该函数添加一个条件语句以仅接受大于0的变量为止.

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;
 }

我期望lcm(15,30)的输出为30,但是我一直收到错误消息,如果在lcm函数中删除delete if语句可以正常工作,但是我希望程序为以下情况返回错误:例如我用(0,30)

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)

推荐答案

if (v || u <= 0)并不是说如果v小于或等于零,或者u小于或等于零",例如我相信你是这样的.实际上是在说如果v不为零,或者u小于或等于零".

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".

操作a || b测试a是否评估为非零,如果不是,则测试b评估是否为非零.如果ab都不为零,则表达式为true.

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.

在C中,如果关系为true,则相等和关系运算符(例如==!=<><=>=)将生成结果1.如果为假,则允许您在条件表达式中使用它们.

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.

正确的条件是:

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

这篇关于OR,并且少于不按预期的C语言运行的运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆