在Python中,`%`运算符用于取模运算,即计算两个数相除后的余数。以下是一些使用`%`运算符计算百分比的例子:
1. 计算百分比:
```python
计算百分比
numerator = 42
denominator = 50
percentage = (numerator / denominator) * 100
print("%.2f%%" % percentage) 输出:84.00%
2. 字符串格式化输出百分比:
```python
字符串格式化输出百分比
name = "Alice"
age = 30
print("My name is %s and I am %d years old." % (name, age)) 输出:My name is Alice and I am 30 years old.
3. 使用`format()`函数格式化百分比:
```python
使用format()函数格式化百分比
print("The percentage is {:.2%}".format(0.75)) 输出:The percentage is 75.00%
4. 从命令行参数计算百分比:
```python
从命令行参数计算百分比
import sys
a = float(sys.argv)
b = float(sys.argv)
print("%.2f%%" % (a / b * 100)) 输出:例如:python calculator.py 3 11 输出:30.00%
以上示例展示了如何使用`%`运算符进行百分比的计算和输出。