[C++] 四捨五入取到小數點後某一位

  • 34969
  • 0
  • C++
  • 2017-07-31

本篇文章介紹如何用C++自行實作四捨五入取到小數點後某一位的功能

開發環境

 

以下程式呼叫一個名為 rounding(double num, int index) 的function,

傳入要被四捨五入的值(num)、四捨五入到小數點以後第幾位(index),

接著回傳一個型態為double的值,

即為原值經過四捨五入以後的結果。

 

程式碼

round.cpp

#include <iostream>
#include <cmath>
using namespace std;
double rounding(double, int);
int main()
{
    double num;  // 要被四捨五入的數字 
    int decPointDigit;  // 小數點後第幾位 
    while(true){
        cout << "Input a number: ";
        cin >> num;
        cout << "Rounded to one decimal after the first of several: ";
        cin >>  decPointDigit;
        num = rounding(num, decPointDigit);
        cout << "After rounding the result is: " << num << endl;
        cout << "===================================================" << endl;
    }
    return 0;
}

// 四捨五入 取到 小數點第 X 位 
double rounding(double num, int index)
{
    bool isNegative = false; // whether is negative number or not
	
    if(num < 0) // if this number is negative, then convert to positive number
    {
        isNegative = true;	
        num = -num;
    }
	
    if(index >= 0)
    {
        int multiplier;
        multiplier = pow(10, index);
        num = (int)(num * multiplier + 0.5) / (multiplier * 1.0);
    }
	
    if(isNegative) // if this number is negative, then convert to negative number
    {
        num = -num;
    }
	
    return num;
}

 

執行結果:

如果這篇文章有幫助到你,想支持一下作者可以幫忙點擊側欄的「 Goolgle AdSense 」廣告 😄

如果你喜歡這篇文章可以點擊「分享」按鈕,來分享到你的網路社群
(以上文章內容如有謬誤,敬請不吝指教)