酷代码 AI
菜单

P2271计算一串数字的和 标准IO 传统题 来源 TomAnderson 时间限制 1000ms 内存限制 256MB 通过/尝试次数 20327/43961 题目描述 禾木想计算一串数字的和,这串数字以0结束。 你来编写代码帮助禾木实现吧! 输入 一行若干个整数,以0结束。 输出 这一串数字的和。 样例 input1 复制 10 9 8 7 6 5 4 3 2 1 0 output1 复制 55

以下是使用Python语言解决该问题的代码: ```python # 初始化总和为 0 total = 0 # 读取输入的一行数据,并按空格分割成数字列表 numbers = list(map(int, input().split())) # 遍历数字列表,直到遇到 0 为止 for num in numbers: if num == 0: break total = total + num # 输出总和 print(total) ``` 以下是使用Java语言解决该问题的代码: ```java import java.util.Scanner; public class Main { public static void main(String[] args) { // 创建 Scanner 对象用于读取输入 Scanner scanner = new Scanner(System.in); int total = 0; // 循环读取输入的整数 while (true) { int num = scanner.nextInt(); if (num == 0) { break; } total = total + num; } // 输出总和 System.out.println(total); // 关闭 Scanner 对象 scanner.close(); } } ``` 以下是使用C++语言解决该问题的代码: ```cpp #include <iostream> using namespace std; int main() { // 初始化总和为 0 int total = 0; int num; // 循环读取输入的整数 while (true) { cin >> num; if (num == 0) { break; } total = total + num; } // 输出总和 cout << total << endl; return 0; } ``` [2026-01-31 21:02:35 | AI问答 | 376点数解答]

服务商
相关提问
发财导航,免费问AI
实用工具查看更多