簡體   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