round 函数

Nannan Lv5

round 函数

要求四舍五入的情况,用round函数就很方便。

一、用法

1.基本用法

对于小数而言,round()函数仅仅保留到整数位,仅对小数点后一位进行四舍五入。

比如:round(1.5) = 2.000000,round(1.57) = 2.000000

2.保留小数用法

如果想要保留小数位数可以先乘后除以达到效果

举个栗子:

1
2
3
4
5
6
7
8
9
10
#include<bits/stdc++.h>
using namespace std;

int main()
{
double x = 1.5684;
//想要保留2位小数
printf("%.2lf\n",round(x*100)/100);//输出是1.57
return 0;
}

二、手写版本

1
2
3
4
double round(double x)
{
return (int)(x+0.5);
}

三、例题

[abc273_b](B - Broken Rounding (atcoder.jp) )

题意:给你一个非负整数,求对进行以下操作次的结果

操作:对数字进行四舍五入操作。

比如:按照四舍五入就是四舍五入就是

思路:先变成小数,对其进行保留到整数位的四舍五入,在乘回来。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

int main()
{
ll x;
int k;
cin>>x>>k;
ll r = 1;

for(int i = 1;i<=k;i++)
{
r*=10;
x = round(x/(long double)r)*r;
}
cout<<x<<endl;
return 0;
}
  • Title: round 函数
  • Author: Nannan
  • Created at : 2023-07-09 12:36:00
  • Updated at : 2024-09-30 21:06:37
  • Link: https://redefine.ohevan.com/2023/07/09/round/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments