【问题标题】:Why is my compiler not showing an error when I'm using '=' instead of '==' in if conditional statement?为什么当我在 if 条件语句中使用 '=' 而不是 '==' 时我的编译器没有显示错误?
【发布时间】:2021-07-18 13:07:12
【问题描述】:

我是 C 编程的初学者,正在练习一个程序,使用数组在 10 个数字中找到最大的数字。

所以,在第一个程序中,编译器发出警告:

警告:建议在赋值周围使用括号作为真值[-W括号]|

但不是错误,这意味着程序正在运行,但我输入的数字始终显示为最大数字。

第二个运行良好并且显示正确的输出。所以,我的问题是为什么编译器只在第一个程序中显示警告而不显示错误?

我认为没有像 '=' 这样的运算符,所以在我的情况下,代码不能运行,但为什么只有警告而不是错误?

第一个程序:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int x, i;
float a [10];
printf("Enter 10 numbers: ");

for (i = 0; i<=9; i++)
    {
        scanf("%f",&a[i]);
    }

for (i =0; i<=9; i++)
    {
        x =0;
        for (int j =0; j<=9; j++)
        {
            if (a[i]>a[j])
                {
                    x++;
                }
        }

        if (x = 9)
        {
        printf("The greatest number is %f",a[i]);
        break;
        }  
    }
}

第二个节目:

#include <stdio.h>
#include <stdlib.h>

int main()
{
int x, i;
float a [10];
printf("Enter 10 numbers: ");

for (i = 0; i<=9; i++)
    {
        scanf("%f",&a[i]);
    }

for (i =0; i<=9; i++)
    {
        x =0;
        for (int j =0; j<=9; j++)
        {
            if (a[i]>a[j])
                {
                    x++;   
                }
        }

        if (x == 9) //replaced '=' in the first program with '=='
        {
        printf("The greatest number is %f",a[i]);
        break;
        }
    }   
}

注意:我正在使用代码块和 MINGW 编译器

【问题讨论】:

  • “因为我认为没有像'='这样的运算符” - 但是有。你每次做作业都会用到它。
  • 问题显然与machine-learning 无关 - 请不要向无关标签发送垃圾邮件(已删除)。

标签: c compiler-errors operators warnings


【解决方案1】:

这不是错误,= 是赋值运算符,您可以在 if 语句中使用赋值运算符。

由于它不常用,编译器会警告您,以验证这是否确实是您想要做的,它不是强制执行的,但它是一项安全功能。

这样的赋值,在if 语句中将始终为真,除非赋值为 0,在这种情况下,条件将评估为假。

请注意,如果您想将警告视为错误,您可以使用-Werror 标志,实际上我认为这样做是个好主意。

【讨论】:

    【解决方案2】:

    x=9 实际上是一个有效的运算符,但它每次运行时都将 x 设置为 9。由于没有真正的条件语句,因此每次运行时都会导致结果为真。但它不会抛出错误!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-30
      • 1970-01-01
      • 2018-10-10
      • 1970-01-01
      • 2019-06-27
      • 2019-11-26
      • 1970-01-01
      相关资源
      最近更新 更多