OR 和小于运算符不按预期的 C 语言工作
OR and less than operators not working as intended C language
我正在做一本名为《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 语句工作正常,但我希望程序 return 一个错误,例如我使用 (0, 30)
if (v || u <= 0)
并不是说 "if v
is less than or equal to zero OR if u
is less than or equal to zero",就像我相信你认为的那样。它实际上是在说 "if v
is not zero, OR u
is less than or equal to zero".
运算 a || b
测试 a
是否为非零,如果不是,则测试 b
是否为非零。如果 a
或 b
非零,则表达式为真。
在 C 中,等于和关系运算符如 ==
、!=
、<
、>
、<=
和 >=
产生如果关系为真,结果 1
,如果关系为假,结果 0
,允许您在条件表达式中使用它们。
正确的条件是:
if (v <= 0 || u <= 0)
if (v || u <= 0)
将 v 视为布尔变量,因此它对每个非零值都成立。所以你的 if 对于任何非零 v 都是真的。
使用 if (v <= 0 || u <= 0)
我正在做一本名为《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 语句工作正常,但我希望程序 return 一个错误,例如我使用 (0, 30)
if (v || u <= 0)
并不是说 "if v
is less than or equal to zero OR if u
is less than or equal to zero",就像我相信你认为的那样。它实际上是在说 "if v
is not zero, OR u
is less than or equal to zero".
运算 a || b
测试 a
是否为非零,如果不是,则测试 b
是否为非零。如果 a
或 b
非零,则表达式为真。
在 C 中,等于和关系运算符如 ==
、!=
、<
、>
、<=
和 >=
产生如果关系为真,结果 1
,如果关系为假,结果 0
,允许您在条件表达式中使用它们。
正确的条件是:
if (v <= 0 || u <= 0)
if (v || u <= 0)
将 v 视为布尔变量,因此它对每个非零值都成立。所以你的 if 对于任何非零 v 都是真的。
使用 if (v <= 0 || u <= 0)