You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Bash脚本实现整数求和?现有代码问题排查

Let's break down the issues in your script and fix them step by step:

Key Problems in the Original Code

  • Case sensitivity: Bash commands and variables are case-sensitive. Your first line uses Read (capital R) which isn't a valid built-in command, and you initialized Sum=0 but later referenced sum (lowercase)—these are two separate variables, so your initial 0 value was never being used.
  • String concatenation instead of arithmetic: The line sum=sum+number just combines text strings ("sum", "+", and the input number) instead of performing actual integer addition. Bash requires explicit syntax to do math operations.

Corrected Script

#!/bin/bash
read N
sum=0
for ((i=1; i<=N; i++))
do
    read number
    sum=$((sum + number))
done
echo $sum

Explanation of Fixes

  1. Fixed input command: Changed Read to lowercase read so Bash recognizes it as the standard input-reading command.
  2. Consistent variable naming: Used lowercase sum throughout to ensure the initial 0 value is properly updated with each iteration.
  3. Arithmetic expansion: Replaced sum=sum+number with sum=$((sum + number)). The $((...)) syntax tells Bash to evaluate the expression inside as a numerical calculation, not string concatenation.

Alternative Concise Version

You can also use the let built-in for shorter arithmetic assignment:

#!/bin/bash
read N
sum=0
for ((i=1; i<=N; i++))
do
    read number
    let sum+=number
done
echo $sum

Both versions will correctly sum your input integers. For example, if you enter 3 when prompted for N, then input 1, 2, 3, the script will output 6.

内容的提问来源于stack exchange,提问作者Kate

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 08:16:10