編程學習網(wǎng) > 編程語言 > C/C++開發(fā) > c語言四舍五入的函數(shù)有哪些?
2022
08-22

c語言四舍五入的函數(shù)有哪些?

四舍五入是財務工作中經(jīng)常遇到的一類問題,也是使用最為頻繁的操作。今天就與大家聊一下c語言四舍五入的函數(shù)有哪些?

or 函數(shù)


功能:把一個小數(shù)向下取整,即就是如果數(shù)是2.4,那向下取整的結(jié)果就是2.000000

原型:double floor(double x); x 是需要計算的數(shù)

返回值:

成功:返回一個double類型的數(shù),此數(shù)默認有6位小數(shù),無失敗的返回值。

頭文件:#include<math.h>

#include<stdio.h>#include<math.h>int main(){  double a = floor(2.4);  double b = floor(-2.4);  printf("a = %f\n", a);  printf("b = %f\n", b); return 0;}
$ ./testa = 2.000000b = -3.000000

floor 函數(shù)把轉(zhuǎn)換后的結(jié)果強轉(zhuǎn)為int類型:

#include<stdio.h>#include<math.h>int main(){ int a = floor(2.4); int b = floor(-2.4);  printf("a = %d\n", a);  printf("b = %d\n", b); return 0;}
$ ./testa = 2b = -3

把計算結(jié)果強轉(zhuǎn)為int后,會丟失精度

ceil 函數(shù)

功能:把一個小數(shù)向上取整,即就是如果數(shù)是2.4,那向上取整的結(jié)果就是3.000000

原型:double ceil(double x), x 是需要計算的數(shù)

返回值:

成功:返回一個double類型的數(shù),此數(shù)默認有6位小數(shù),無失敗的返回值。

頭文件:#include<math.h>

#include<stdio.h>#include<math.h>int main(){  double a = ceil(2.4);  double b = ceil(-2.4);  printf("a = %f\n", a);  printf("b = %f\n", b); return 0;}
$ ./testa = 3.000000b = -2.000000

ceil 函數(shù)把計算后的結(jié)果強轉(zhuǎn)為int類型的:

#include<stdio.h>#include<math.h>int main(){ int a = ceil(2.4); int b = ceil(-2.4);  printf("a = %d\n", a);  printf("b = %d\n", b); return 0;}
$ ./testa = 3b = -2
round 函數(shù)

功能:把一個小數(shù)四舍五入,就是如果數(shù)是2.4, 那四舍五入的結(jié)果就為2;如果數(shù)是2.5,那結(jié)果就是3。

原型:double round(double x); x 指的是需要計算的數(shù)。

頭文件:#include<math.h>

#include<stdio.h>#include<math.h>int main(){  double a = round(2.4);  double b = round(2.8);  double c = round(-2.4);  double d = round(-2.8);  printf("a = %f\n", a);  printf("b = %f\n", b);  printf("c = %f\n", c);  printf("d = %f\n", d); return 0;}
$ ./testa = 2.000000b = 3.000000c = -2.000000d = -3.000000

以上就是“c語言四舍五入的函數(shù)有哪些?”的詳細內(nèi)容,想要了解更多C語言教程歡迎持續(xù)關注編程學習網(wǎng)

掃碼二維碼 獲取免費視頻學習資料

Python編程學習

查 看2022高級編程視頻教程免費獲取