为什么这样写不行呢

Raemo  •  1年前


// 输入一个浮点数,实现小数点后第3位的四舍五入,例如输入1.235,输出1.24。
#include<bits/stdc++.h>
using namespace std;
int main(){
    double d;
    cin>>d;
    d = (int)(d*1000+5); //扩大千倍再加5,使小数点后的第三位加5,实现四舍五入
    // 再除以10,以实现保留两位,但此法会导致小数位全为0的数最终输出不带小数位,固最后设置输出格式,同时舍去此处的除以10
    cout<<d<<endl;
    d/=1000.0;
    cout<<setprecision(2)<<fixed<<d;
    return 0;
}

评论:

你输出多了啊。。。


ZZQ  •  1年前

而且setprecision会直接截取位数,不会四舍五入


ZZQ  •  1年前
#include<bits/stdc++.h>
using namespace std;
int main(){
    double d;
    cin>>d;
    cout<<setprecision(2)<<fixed<<d<<endl;
    return 0;
}

这样反而行了


maplesky  •  1年前

zdx  •  1年前

double换成float试试 中间一大段删掉,只留定义,输入,输出 cout<<fixed<<setprecision(2)<<d<<endl;(亲测有效)


Jαγ  •  1年前

不是你这啥玩意啊

正确做法

include<bits/stdc++.h>

using namespace std; int main(){

double d;
cin>>d;
cout<<setprecision(2)<<fixed<<d<<endl;
return 0;

}


魈凯KBS  •  4个月前