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

火山引擎 最新活动