3.浮点数的应用

一、定义浮点数

在C++中,有两种数据类型都可以表示小数

数据类型 定义标识符 有效位数
单精度浮点类型 float 6-7位
双精度浮点类型 double 15-16位

二、类型转换

double f=3;int a=2;
cout<<f/a; //1.5
int a=1.23;
cout<<a; //1
double a=1;
cout<<(int)a/2; //0

三、保留小数

#include <iostream>
#include <iomanip>
using namespace std;
int main(){
	float b=3.1415;
	double d=3.141567;
	cout<<setprecision(3)<<b<<endl; //3.14
	cout<<fixed<<setprecision(3)<<d<<endl; //3.142
	cout<<setprecision(1)<<fixed<<d<<endl; //3.1
	return 0;
}
注意:头文件需加上iomanip

四、数学函数

函数 解释 返回值类型 举例 结果
abs(x) 求绝对值 数字 abs(-4) 4
sqrt(x) 平方根 浮点型 sprt(6) 2.449
floor(x) 向下取整 整型 floor(3.6) 3
ceil(x) 向上取整 整型 ceil(3.1) 4
max(x,y) 最大值 数字 max(1,3) 3
min(x,y) 最小值 数字 min(1,3) 1
注意:头文件需加上cmath

五、基本数字知识

平方根:如果一个非负数x的平方等于a,即x*x=a,那么x就是a的平方根
绝对值:非负数(正数和0)的绝对值是它本身,非正数(负数和0)的绝对值是它的相反数

posted @ 2025-08-11 14:44  JYR2015  阅读(10)  评论(0)    收藏  举报