gpt4 book ai didi

python - 如何在 Python 中一行输入 2 个整数?

转载 作者:太空狗 更新时间:2023-10-29 19:34:10 24 4
gpt4 key购买 nike

我想知道是否可以在一行标准输入中输入两个或多个整数。在 C/C++ 中很简单:

C++:

#include <iostream>
int main() {
int a, b;
std::cin >> a >> b;
return 0;
}

C:

#include <stdio.h>
void main() {
int a, b;
scanf("%d%d", &a, &b);
}

Python 中,它不会工作:

enedil@notebook:~$ cat script.py 
#!/usr/bin/python3
a = int(input())
b = int(input())
enedil@notebook:~$ python3 script.py
3 5
Traceback (most recent call last):
File "script.py", line 2, in <module>
a = int(input())
ValueError: invalid literal for int() with base 10: '3 5'

那么怎么做呢?

最佳答案

在空格处拆分输入的文本:

a, b = map(int, input().split())

演示:

>>> a, b = map(int, input().split())
3 5
>>> a
3
>>> b
5

关于python - 如何在 Python 中一行输入 2 个整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23253863/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com