我一直在尝试编写一个为我计算因数的程序,但尽管条件为假,但我的 if 语句仍在运行。在函数factor中,我用modf把小数和整数分开,存成c
。 if 语句检查是否 c = 0
这意味着数字被平均分配。
下面是我的源代码及其下方的结果。
#include <iostream>
#include <math.h>
using namespace std;
int factor(double b);
int i = 1;
int factors[] = {1};
int main()
{
int a;
double b;
cout << "Please enter a integer to Factor: ";
cin >> a;
b = a;
factor(b);
return 0;
}
int factor(double b)
{
double c;
double d;
for ( ; c != 0 ; i++)
{
cout << "for loop executed" << endl;
c = modf (b/3, &d);
cout << c << endl;
if (c = 0.00);
{
cout << 3 << endl;
factors[i] = 3;
continue;
}
c = modf (b/5, &d);
if (c = 0);
{
cout << 5 << endl;
factors[i] = 5;
continue;
}
c = modf (b/7, &d);
if (c = 0);
{
cout << 7 << endl;
factors[i] = 7;
continue;
}
c = modf (b/11, &d);
if (c = 0);
{
cout << 11 << endl;
factors[i] = 11;
continue;
}
c = modf (b/13, &d);
if (c = 0);
{
cout << 13 << endl;
factors[i] = 13;
continue;
}
c = modf (b/17, &d);
if (c = 0);
{
cout << 17 << endl;
factors[i] = 17;
continue;
}
}
return c;
}
在cmd中打印
Please enter a integer to Factor: 50
for loop executed
0.666667
3
50/3=16.6 次重复
16.6666666 的 modf 输出 16 和 0.666667
0.666667 不等于 0,所以我很困惑。
最佳答案
显示的代码中存在多个错误。
double c;
for ( ; c != 0 ; i++)
c
变量未初始化,然后将其值与 0 进行比较。这是未定义的行为。
if (c = 0.00);
这里一行有两个错误。
=
是赋值运算符,不是比较运算符。 if
表达式在此处的计算结果始终为 false。
然后,右括号后面的额外分号终止了 if
语句。紧接着:
{
cout << 3 << endl;
factors[i] = 3;
continue;
}
这将始终被执行,因为它实际上并不是前面 if
语句的一部分。
==
是比较运算符。
=
是赋值运算符。
if()
表达式后没有分号。如果是,它将被解释为一个空语句。
但是,问题还没有结束:
int i = 1;
int factors[] = {1};
这声明了包含一个值的数组factors
。数组的大小是 1 个元素。
for ( ; c != 0 ; i++)
// ...
factors[i] = 3;
这将尝试分配数组中不存在的元素,超出数组末尾并破坏内存。
令我惊讶的是,所有这些都设法运行了很多次迭代,但是,好吧,这就是“未定义行为”的意思。
关于C++ if 命令读取 true 尽管 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39009006/