【问题标题】:OR and less than operators not working as intended C languageOR 和小于运算符不能按预期工作 C 语言
【发布时间】:2019-06-19 18:35:04
【问题描述】:

我正在做一本名为“用 C 语言编程”的书的练习,试图解决练习 7.9,因此我的代码可以完美运行,直到我为函数添加条件语句以仅接受大于 0 的变量

我尝试了很多方法来改变它,但似乎没有任何效果

// 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 de if 语句可以正常工作,但我希望程序在以下情况下返回错误例如我使用 (0, 30)

【问题讨论】:

    标签: c logical-operators relational-operators


    【解决方案1】:

    if (v || u &lt;= 0) 并不是说​​“如果v 小于或等于零,或者如果u 小于或等于零”,就像我相信您认为的那样。它实际上是在说“如果v 不为零,或者u 小于或等于零”。

    操作a || b 测试a 的计算结果是否为非零,如果不是,则测试b 的计算结果是否为非零。如果ab 不为零,则表达式为真。

    在 C 中,等式和关系运算符,如 ==!=&lt;&gt;&lt;=&gt;=,如果关系为真,则生成结果 1,以及 0如果为 false,则允许您在条件表达式中使用它们。

    正确的条件是:

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

    【讨论】:

    • 非常感谢您的回复。
    【解决方案2】:

    if (v || u &lt;= 0) 将 v 视为布尔变量,因此对于每个非零值都为真。所以你的 if 对于任何非零 v 都是真的。 使用if (v &lt;= 0 || u &lt;= 0)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-24
      • 1970-01-01
      • 1970-01-01
      • 2021-06-12
      • 1970-01-01
      相关资源
      最近更新 更多