This commit is contained in:
2024-10-24 09:27:08 +08:00
parent db7ef40fa7
commit 2cfce434a9
4 changed files with 97 additions and 1 deletions

74
src/learn/04/index.md Normal file
View File

@@ -0,0 +1,74 @@
经常会有输出要保留N位小数的情况比如[1046 圆的面积](https://oj.xuyue.cc/problem/1046) 这道题需要保留4位小数
## "%.2f" % 方法
使用方法如下:
```py
a=1.23456
print("%.4f" % a)
print("%.3f" % a)
print("%.2f" % a)
```
得到的结果
```py
1.2346
1.235
1.23
```
这个方法**会进行四舍五入**
### 注意:"%.2f" % 后面只能跟着一个变量或运算结果,不能跟着计算表达式
下面代码运行会**报错**
```py
a=10
b=3
print(".2f" % a/b) # 这里是错误的❌
```
可以改成:
```py
a=10
b=3
c=a/b
print(".2f" % c) # 这样是正确的✔
```
或者,把计算表达式用括号包起来
```py
a=10
b=3
print(".2f" % (a/b)) # 这样是正确的✔
```
## format() 函数
使用方法如下:
```py
a=1.23456
print(format(a, ".4f"))
print(format(a, ".3f"))
print(format(a, ".2f"))
```
**不要忘记小数点**
得到的结果
```py
1.2346
1.235
1.23
```
这个方法**会进行四舍五入**

9
src/learn/04/main.py Normal file
View File

@@ -0,0 +1,9 @@
a=1.23456
print('%.4f' % a)
print('%.3f' % a)
print('%.2f' % a)
print(format(a, ".2f"))
print(format(a, ".3f"))
print(format(a, ".4f"))

View File

@@ -118,4 +118,16 @@ html.dark .shiki span {
font-size: 20px;
font-family: "Monaco";
}
.markdown-body h2 {
font-size: 24px;
}
.markdown-body h3 {
font-size: 22px;
}
.markdown-body p {
font-size: 18px;
}
</style>

View File

@@ -1,3 +1,4 @@
输出函数 print() 的使用
输入函数 input() 需要注意的地方
输入用空格隔开,如何写
输入用空格隔开,如何写
输出保留N位小数