读到结束标记(哨兵)的循环顺序是“读入 → 判断是否为 0 → 处理”。 把读入和判断写在一行:Python while (x := int(input())) != 0:(3.8 的海象运算符),C while (scanf("%lld", &x) == 1 && x != 0),C++ while (std::cin >> x && x != 0),Java/C# while ((x = …parse(readLine())) != 0)。 JS/TS 一次读入全部输入,在 for … of 中遇到 0 就 break。 Craykon 不能在表达式里赋值,所以在循环前先读一次,在循环末尾再读下一行(x = 控制台.读行().转数字();)。 三个陷阱:① 读到输入结束(EOF)会把 0 之后的行也加进去(第二个示例)。 ② 先处理再判断 0,会为 0 多输出一行和。 ③ 和最大可达 10^9 × 10^4 = 10^13,C、C++、Java、C# 需要 long(long long)。 Python 整数不会溢出,JS/TS/Craykon 的浮点数在 2^53(约 9×10^15)以内是精确的,没有问题。
Pythonmain.py · 5 行
total = 0# 0이 끝 표시다. 0 뒤에 줄이 더 있어도 읽지 않는다while (x := int(input())) != 0: total += x print(total)
JavaScriptmain.js · 9 行
const nums = require("fs").readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const out = [];let total = 0;for (const x of nums) { if (x === 0) break; // 끝 표시. 뒤에 남은 수는 무시 total += x; out.push(total);}console.log(out.join("\n"));
TypeScriptmain.ts · 10 行
import { readFileSync } from "node:fs";const nums: number[] = readFileSync(0, "utf8").trim().split(/\s+/).map(Number);const out: number[] = [];let total = 0;for (const x of nums) { if (x === 0) break; // 끝 표시. 뒤에 남은 수는 무시 total += x; out.push(total);}console.log(out.join("\n"));
JavaMain.java · 17 行
import java.io.BufferedReader;import java.io.InputStreamReader;public class Main { public static void main(String[] args) throws Exception { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); long total = 0; // 10^9 × 10^4 = 10^13 이라 int로는 넘친다 long x; // 0이 끝 표시다. 0 뒤의 줄은 읽지 않는다 while ((x = Long.parseLong(br.readLine().trim())) != 0) { total += x; out.append(total).append('\n'); } System.out.print(out); }}
C#Main.cs · 19 行
using System;using System.Text;class Program{ static void Main() { var out_ = new StringBuilder(); long total = 0; // 10^9 × 10^4 = 10^13 이라 int로는 넘친다 long x; // 0이 끝 표시다. 0 뒤의 줄은 읽지 않는다 while ((x = long.Parse(Console.ReadLine())) != 0) { total += x; out_.Append(total).Append('\n'); } Console.Write(out_); }}
C++main.cpp · 12 行
#include <iostream>int main() { std::ios::sync_with_stdio(false); std::cin.tie(nullptr); long long x, total = 0; // 10^9 × 10^4 = 10^13 이라 int로는 넘친다 // 0이 끝 표시다. 0 뒤의 줄은 읽지 않는다 while (std::cin >> x && x != 0) { total += x; std::cout << total << '\n'; }}
Cmain.c · 11 行
#include <stdio.h>int main(void) { long long x, total = 0; /* 10^9 × 10^4 = 10^13 이라 int로는 넘친다 */ /* 0이 끝 표시다. 0 뒤의 줄은 읽지 않는다 */ while (scanf("%lld", &x) == 1 && x != 0) { total += x; printf("%lld\n", total); } return 0;}
Craykonmain.cray · 9 行
합 = 0;x = 控制台.读行().转数字();// 0이 끝 표시다. 0 뒤의 줄은 읽지 않는다当 (x != 0){ 합 += x; 控制台.输出(합); x = 控制台.读行().转数字();}