C语言80分求助

B2046 骑车与走路

Austin_Shen @ 2023-04-06 15:10:12

 #include<stdio.h>

int main() {
    int distence;
    scanf("%d",&distence);
    if(distence/1.2>(distence+150)/3.0){
        printf("Bike");
    } else if(distence/1.2==(distence+150)/3.0){
        printf("All");
    } else if(distence/1.2<(distence+150)/3.0){
        printf("Walk");
    }
    return 0;
    }

by Terrible @ 2023-04-06 16:05:43

>>> distence=100
>>> distence/1.2==(distence+150)/3.0
False
>>> print("%.100f"%(distence/1.2),"%.100f"%((distence+150)/3.0),sep='\n')
83.3333333333333428072364768013358116149902343750000000000000000000000000000000000000000000000000000000
83.3333333333333285963817615993320941925048828125000000000000000000000000000000000000000000000000000000

可见两者并没有相等,有浮点误差时不能判等的。可以消除浮点误差或者提供一个接受更高的浮点误差的方法。@Austin_Shen

distence/1.2==(distence+150)/3.0 两边同时乘以 6 可转写为 distence*5==(distence+150)*2,当然不等式也应当注意这一问题。

或者给判断提供一个误差值,普遍使用eps=1e-9;,例如 fabs(x-y)<eps,以表明 xy 值相差不到 10^{-9}

Moreover, ur spelling is wrong. That "distence" should be spelt as "distance".


by liyandong @ 2023-06-09 23:08:31

a=int(input())
t=a/3.0+23+27
t1=a/1.2
if t>t1:
    print("Walk")
if t<t1:
    print("Bike")
if t==t1:
    print("All")

用Python多好的


|