[Day-25] math函式库(一)

今天要来练习的是
C++内建的函式库
首先要先引入函式库

#include <cmath>

今天会着重练习
比较常用也比较简单的函式
「cmath」就是主要是数学运算的函式
等等会练习的有以下几点:
◆四舍五入
◆向上取整
◆向下取整
◆无条件舍去

以下就开始今天的练习罗

1. 四舍五入

程序码:

#include <iostream>
#include <math.h>
using namespace std;

int main(){
	float s[4]= {1.3, 8.7, 46.5, 11.1};

	for(int i = 0; i<=3; i++){
		cout << roundf(s[i]) <<'\n'; 
	}
	
	return 0;
}

执行结果:

1
9
47
11
--------------------------------
Process exited after 0.08787 seconds with return value 0
请按任意键继续...

使用roundf()的函式就能用数学运算出四舍五入的结果
这边回传的值为float

2.向上取整

程序码:

#include <iostream>
#include <math.h>
using namespace std;

int main(){
	float s[4]= {1.3, 8.7, 46.5, 11.1};

	for(int i = 0; i<=3; i++){
		cout << ceil(s[i]) <<'\n'; 
	}
	
	return 0;
}

执行结果:

2
9
47
12
--------------------------------
Process exited after 0.08787 seconds with return value 0
请按任意键继续...

使用ceil()的函式就能用数学运算出向上取整的结果
这边回传的值为float

3.向下取整

程序码:

#include <iostream>
#include <math.h>
using namespace std;

int main(){
	float s[4]= {1.3, 8.7, 46.5, 11.1};

	for(int i = 0; i<=3; i++){
		cout << floor(s[i]) <<'\n'; 
	}
	
	return 0;
}

执行结果:

1
8
46
11
--------------------------------
Process exited after 0.08787 seconds with return value 0
请按任意键继续...

使用floor()的函式就能用数学运算出向下取整的结果
这边回传的值为float

4.无条件舍去

程序码:

#include <iostream>
#include <math.h>
using namespace std;

int main(){
	float s[4]= {1.3, 8.7, 46.5, 11.1};

	for(int i = 0; i<=3; i++){
		cout << trunc(s[i]) <<'\n'; 
	}
	
	return 0;
}

执行结果:

1
8
46
11
--------------------------------
Process exited after 0.08787 seconds with return value 0
请按任意键继续...

使用trunc()的函式就能用数学运算出无条件舍去的结果
这边回传的值为float
/images/emoticon/emoticon07.gif

学会了以上基本的数学运算
就可以应用在很多地方上
程序码就不会太冗长
今天就练习到这边罗~
下次会再练习更多关於函式库「cmath」里面的函式
/images/emoticon/emoticon08.gif

-End-


<<:  Day 28: Tensorflow分类 分类图像衣物 (三)

>>:  EP19 - [TDD] 订单 API 串接 (2/2)

[重构倒数第30天] - 使用 Vue3 Composition API 重构 JS 选单

前言 该系列是为了让看过Vue官方文件或学过Vue但是却不知道怎麽下手去重构现在有的网站而去规画的系...

【心得】你今天种菜了吗? grid之路-grid的使用(2)

前言 昨天介绍了用grid-template-areas 来填格子 grid-template-ar...

Day 16:架设 Grafana (2)

看来今天终於是可以把 Grafana 的章节结束掉了,之前提到我觉得目前找到的 dashboard ...

DAY18 MongoDB Replication 实战

DAY18 MongoDB Replication 实战 本篇我们要使用 Dcoker compos...

30天零负担轻松学会制作APP介面及设计【DAY 28】

大家好,我是YIYI,今天我要来跟大家聊聊ICON。 ICON设计原则 我认为最重要的原则就是清晰,...