終わりの印(番兵)まで読むループは「読む → 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 = コンソール.行読み().数に();}