求指正

P5719 【深基4.例3】分类平均

xsy001 @ 2023-07-21 21:56:57


#include <iostream> 
using namespace std;
int main(){
    float c,d,a=0,b=0,e=0,f=0;
    int x=1,n,k;
    cin>>n>>k;
    while(x<=n){
        if(x%k==0){
            a=a+x;
            e++;
        }else{
            b=b+x;
            f++;
        }
        x++;

    }
    c=a/e;
    d=b/f;
    printf("%.1f ",c);
    printf("%.1f",d);
}

by _ZXWDS @ 2023-07-21 22:20:12

数据类型改double


by _ZXWDS @ 2023-07-21 22:22:13

@xsy001


by xsy001 @ 2023-07-21 22:25:32

@_ZXWDS 能否讲解一下,用double就好了? 谢谢


by _ZXWDS @ 2023-07-21 22:33:00

@xsy001 float是单精度,在用float进行除法的时候,精度不够,会出现误差


by _ZXWDS @ 2023-07-21 22:33:58

@xsy001 double的范围大,这种题用double避免误差,,


by _ZXWDS @ 2023-07-21 22:35:34

@xsy001 具体的话,建议您看这个了解具体区别


by bk1212 @ 2023-07-21 22:45:56

@xsy001 因为float是单精度浮点数,而double是双精度浮点数,程序处理上float比double快,但是double储存空间比float大,应该因为这个吧,float会爆


by xsy001 @ 2023-07-21 23:01:02

@_ZXWDS 感谢解惑


|