C++ float型整数除以int型整数 控制两位小数输出
时间: 2023-12-24 15:03:43 浏览: 45
可以使用 C++ 中的格式化输出控制符来控制输出的小数位数。具体实现如下:
```c++
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
float f = 10.0;
int i = 3;
float result = f / i;
cout << fixed << setprecision(2) << result << endl;
return 0;
}
```
在这段代码中,`fixed` 控制定点输出格式,`setprecision(2)` 控制小数位数为 2。运行结果为 `3.33`,即将 `f / i` 的结果控制在两位小数以内输出。
相关问题
C++保留一位小数没有四舍五入
如果你想保留一位小数,而不进行四舍五入,可以使用下面的方法:
1. 用 `floor()` 函数将小数点后一位以下的部分舍去。
```c
#include <stdio.h>
#include <math.h>
int main() {
float num = 3.1415926;
num = floor(num * 10) / 10;
printf("%.1f", num);
return 0;
}
```
输出结果为 `3.1`。
2. 或者将原数乘以 10,取整数部分,再除以 10。
```c
#include <stdio.h>
int main() {
float num = 3.1415926;
num = ((int)(num * 10)) / 10.0;
printf("%.1f", num);
return 0;
}
```
输出结果为 `3.1`。
c++编程实现使一任意实型正数保留2位小数,并对第三位进行四舍五入
可以使用以下代码实现:
```c
#include <stdio.h>
int main() {
float num;
printf("请输入一个实型正数:");
scanf("%f", &num);
num = (int)(num * 100 + 0.5) / 100.0;
printf("保留2位小数后的结果为:%.2f\n", num);
return 0;
}
```
这段代码会让用户输入一个实型正数,然后将其乘以100并加上0.5,再取整数部分,最后除以100.0,从而保留2位小数并进行四舍五入。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)