C/C++整数除法以及保留小数位的问题

题目描述

Given two postive integers A and B, please calculate the maximum integer C that C*B≤A, and the real number D equal to A/B.

输入格式

Two integers A and B in one line separated by a space.(A,B>0)

输出格式

Output C in one line,followed by D in one line. D should be round to 2 digits after decimal point.

代码:

#include <iostream> 
#include <iomanip>
using namespace std;


int main()
{
        int a,b;
        cin>>a>>b;
        int C = a / b;
        cout<<C<<endl;
        double e = a, f = b;
        double D = e / f;
        cout<<setprecision(2)<<fixed<<D<<endl;
        return 0;
}

整数除法用 “/”的话得到的是一个整数(得到小数的话自动去掉小数位只保留整数位),所以这里要得到实际除出来的数的话,先将两个数转化为double类型,再进行“/”除法。至于要规定输出保留多少位小数,则用cout<<setprecision(2)<<fixed<<……;其中2表示保留多少位小数(2表示两位)。同时要注意seprecision函数的使用要搭配<iomanip>头文件。关于<iomanip>头文件:

这个头文件是声明一些 “流操作符”的,

比较常用的有:

setw(int);//设置显示宽度。

left//right//设置左右对齐。

setprecision(int);//设置浮点数的精确度。