编写代码,实现将用户输入的十进制整数转换为指定进制(二进制、八进制、十六进制)的功能。要求分别用到%格式化、format()方法、f-string三种方式进行输出。
时间: 2024-09-27 11:11:42 浏览: 38
以下是使用%格式化、format()方法和f-string三种方式分别实现将十进制整数转换为二进制、八进制和十六进制的代码示例:
1. %格式化:
```python
def convert_with_format(num, base):
return '{0:b}'.format(num), '{0:o}'.format(num), '{0:x}'.format(num)
decimal_num = int(input("请输入十进制整数: "))
binary, octal, hexadecimal = convert_with_format(decimal_num, 2)
print(f"二进制: {binary}")
print(f"八进制: {octal}")
print(f"十六进制: {hexadecimal}")
```
2. format()方法:
```python
def convert_with_format_method(num, base):
binary = bin(num)[2:]
octal = oct(num)[2:]
hexadecimal = hex(num)[2:].upper()
return binary, octal, hexadecimal
decimal_num = int(input("请输入十进制整数: "))
binary, octal, hexadecimal = convert_with_format_method(decimal_num)
print(f"二进制: {binary}")
print(f"八进制: {octal}")
print(f"十六进制: {hexadecimal}")
```
3. f-string:
```python
def convert_with_f_string(num, base):
return f"{num:b}", f"{num:o}", f"{num:x}"
decimal_num = int(input("请输入十进制整数: "))
binary, octal, hexadecimal = convert_with_f_string(decimal_num)
print(f"二进制: {binary}")
print(f"八进制: {octal}")
print(f"十六进制: {hexadecimal}")
```
在这三种方法中,用户都需要先输入一个十进制整数,然后程序将其转换为相应的进制并打印出来。
阅读全文