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);//設置浮點數的精確度。



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM