繁体   English   中英

c中具有浮点的模数

[英]Modulus with floating point in c

我在编译以下程序时非法使用浮点错误。 请让我知道我在哪里犯错。

#include<stdio.h>
#include<conio.h>

void main()
{
    float a;
    clrscr();
    printf("\n Enter the num : ");
    scanf("%f", &a);

    if ( a >= 0 )
    {
        if ( (a % 2) == 0 ) //ERROR HERE
        {
            printf("\n You entered a positive even num");
        }
        else
        {
            printf("\n You entered a positive odd num");
        }
    }
    else
    {
        if ( (a % 2) == 0 ) //ERROR HERE
        {
            printf("\n You entered a negative even num");
        }
        else
        {
            printf("\n You entered a negative odd num");
        }
    }
    getch();
}

因为%用于整数类型。 使用fmod()

但是像往常一样,要非常警惕对浮点类型执行相等比较( == 也许在您的情况下,最好始终使用整数类型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM