簡體   English   中英

如何通過輸入避免負數,或者如果用戶輸入負數,程序會給出錯誤結果?

[英]How can i avoid negative number through input or if user input negative number the program gives bug result?

每次用戶輸入兩個值。 結果應該是 ,result = (large number/small number) 總是。 如果用戶給出一個負值和一個正值作為輸入,那么它會產生一個錯誤。

#include<stdio.h>

int main()
{

int times=0;
float a,b,result;

while(times<5)
{
    printf("\nEnter two numbers : \n");
    scanf("%d %d",&a,&b);
    if(a =< 0 || b =< 0)
    {
        printf("INPUT ERROR\n");
    }
    else
    {
        if(a>=b)
        {
            result =a/b;
            printf("The result is = %.2f\n",result);
        }
        else
        {
            result =b/a;
            printf("The result is = %.2f\n",result);
        }
    }

    times++;
}
return 0;
}

我該如何解決這個問題。提前致謝!!!!

您的代碼中有兩個問題:運算符和處理輸入。

如果您想檢查某個東西是否小於/等於其他東西,您應該使用<=>= ,而您正在使用=<運算符,這在(至少)C/C++ 中不存在。

在獲取輸入和使用float變量時,您應該使用與printf相同的占位符,對於float變量,它是%f 如果您決定將其更改為int ,您將使用%d ,但您的結果也將是int

固定代碼:

#include<stdio.h>

int main()
{
    int times = 0;
    float a, b, result;

    while (times < 5)
    {
        printf("\nEnter two numbers : \n");
        scanf("%f %f", &a, &b);
        if(a <= 0 || b <= 0)
        {
            printf("INPUT ERROR\n");
        }
        else
        {
            if(a >= b)
            {
                result = a / b;
                printf("The result is = %.2f\n", result);
            }
            else
            {
                result = b / a;
                printf("The result is = %.2f\n", result);
            }
        }
        times++;
    }
    return 0;
}

還有一個編譯代碼的技巧 - 使用額外的標志,它總是會顯示錯誤,我真的很喜歡使用-Wall -Wextra -Werror -pedantic 它們提供有關“可疑”結構( -Wall )的信息,啟用更多-Wall-Wextra )未啟用的標志,將所有警告更改為錯誤( -Werror )並發出 ISO C 要求的所有警告( -pedantic )。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM