注册 登录
编程论坛 C语言论坛

编译器中能直接加数字? 但是定义之后还是出现一样的结果??编程还挺多??/?

爱c如爱命 发布于 2021-04-08 16:57, 1604 次点击
#include<stdio.h>
#include<math.h>
void main()
{
    float p,w,s;
    double f;
    printf("input three numbers p,w,s\n");
    scanf("%f,%f,%f",&p,&w,&s);
        if(s<250)
        {
            printf("p*w*s=%f",f);
        }
        else if(250<=s<500)
        {
            printf("p*w*s*(0.98)=%d",f);
        }
        else if(500<=s<1000)
        {
            printf("p*w*s*(0.95)=%f",f);
        }

        else if(1000<=s<2000)
        {
            printf("p*w*s*(0.92)=%f",f);
        }
        else if(2000<=s<3000)
        {
            printf("p*w*s*(0.90)=%f",f);
        }
        else if(3000<=s)
        {
            printf("p*w*s*(0.85)=%f",f);
        }
        else printf("错误");
}
运行这个程序是无误的,可就是输出结果一直都是0,是由于编译器中不能直接加数字嘛?但是我也试过将1还有0.98这样数在开头定义过,可运行结果还是错误的。就有点疑惑,然后当运行的时候,右下角还会出现Encoding changed这类字符。请哪位大佬来解决下
5 回复
#2
夏天q2021-04-08 19:04
因为f的值并没有定义,
printf("p*w*s=%f",f);
中""扩起来的是字符串,是什么就显示什么,是不会进行任何运算的,所以这里并没有f=p*w*s。其他项也如此,在输出前给f赋值就行了,代码修改如下
程序代码:
#include<stdio.h>
#include<math.h>
void main()
{
    float p,w,s;
    double f;
    printf("input three numbers p,w,s\n");
    scanf("%f,%f,%f",&p,&w,&s);
        if(s<250)
        {
            f = p*w*s;
        printf("p*w*s=%f",f);
        }
        else if(s<500)
        {
            f = p*w*s*0.98;
            printf("p*w*s*(0.98)=%d",f);
        }
        else if(s<1000)
        {
            f = p*w*s*0.95;
            printf("p*w*s*(0.95)=%f",f);
        }

        else if(s<2000)
        {
            f = p*w*s*0.92;
            printf("p*w*s*(0.92)=%f",f);
        }
        else if(s<3000)
        {
            f = p*w*s*0.90;
            printf("p*w*s*(0.90)=%f",f);
        }
        else if(3000<=s)
        {
            f = p*w*s*0.85;
            printf("p*w*s*(0.85)=%f",f);
        }
        else printf("错误");
}


[此贴子已经被作者于2021-4-9 20:07编辑过]

#3
爱c如爱命2021-04-08 22:17
回复 楼主 爱c如爱命
万分感动,后来也发现自己的错误了
#4
rjsp2021-04-09 08:24
else if(250<=s<500)
应该是 else if( 250<=s && s<500)
而且之前有了 if(s<250),所以这里只需要 else if( s<500 ) 就可以了

程序代码:
#include <stdio.h>

int main( void )
{
    double p,w,s;
    puts( "input three numbers p,w,s" );
    scanf( "%lf%lf%lf", &p, &w, &s );

    double r = 0;
    if( s < 250 )
        r = 1.00;
    else if( s < 500  )
        r = 0.98;
    else if( s < 1000  )
        r = 0.95;
    else if( s < 2000  )
        r = 0.92;
    else if( s < 3000  )
        r = 0.90;
    else
        r = 0.85;

    printf( "%f\n", p*w*s*r );
}
#5
YSA2021-04-10 17:27
你这个程序输出的为啥也是0?
是少r=p*w*s;了吗
#6
夏天q2021-04-11 12:06
回复 5楼 YSA
4楼的代码并没有问题
printf( "%f\n", p*w*s*r );

输出的时候乘上了r
但是
scanf( "%lf%lf%lf", &p, &w, &s );

和作者的代码
scanf("%f,%f,%f",&p,&w,&s);

有区别
如果你运行4楼的代码加了,
则结果就会出现0

[此贴子已经被作者于2021-4-11 12:07编辑过]

1