2016-08-18 97 views
0

我一直在试图编写一个程序,因为我的因素编号,但我的if语句保持运行,尽管条件为假。在函数因子中,我使用modf将整数中的小数分隔并将其存储为c。 if语句检查c = 0是否意味着平均分配的数字。C++如果命令读取真假,尽管虚假

下面是我的源代码,其结果在下面。

#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重复
MODF 16.6666666输出16和0.666667
0.666667的不等于0,所以我很困惑。

+4

区分'='和'=='。 –

+2

'c = 0.00'和'c = 0'是赋值而不是比较,而'if'状态之后的分号将阻止'if'语句完成有意义的工作。这段代码有多难看! – MikeCAT

+2

更糟糕的是,在'c!= 0'的条件下,你使用'c'的不确定值,这是''具有自动存储持续时间的默认初始化变量。 – MikeCAT

回答

1

显示的代码中有多个错误。

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; 

这将尝试分配不存在的数组元素,超出数组末尾并损坏内存。

我感到惊讶的是,所有这些管理都可以运行,对于大量的迭代,但是,这就是“未定义行为”的含义。