设计一个循环,迭代10次并保持输入数字的累加总和。

huangapple go评论57阅读模式
英文:

Need assistance with designing a loop to iterate 10 times and keeping a running total of numbers entered

问题

设计一个循环,要求用户输入一个数字。循环应该迭代10次,并保持输入数字的累计总和。

英文:

"Design a loop that asks the user to enter a number. The loop should iterate 10
times and keep a running total of the numbers entered."

This is the prompt I'm working with. I'm using bash code in Windows Subsystem for Linux. It's an online class and my professor is currently no help because of the start of spring break. I'm not entirely sure what to do because I am new to programming in general (joined the class kind of late).

I'm expecting a loop that should iterate 10 times. It also has to keep a running total of the numbers entered. I know the basics, but when I tried it out myself it felt like I was just doing spaghetti code or something.

答案1

得分: 0

可以使用带有-p选项的read函数,它会打印一个提示。最后的变量将存储用户的回答。

然后,您可以设置一个初始计数变量为1(或0,根据您的喜好)。

接下来,while循环的条件是“只要这个条件为真就一直循环”,其中“这个条件”是包含在[[ ]]内的内容。-le表示“小于或等于”。

((cnt++))表示在每次循环中递增cnt变量。

以下是示例代码:

# 提示用户输入
read -p "请输入循环次数: " max_cnt

# 设置初始计数
cnt=1

# 循环并打印值直到达到max_cnt
while [[ $cnt -le $max_cnt ]]; do
  echo "循环 '$cnt' 的总次数是 '$max_cnt'"
  ((cnt++))
done

例如:

$ read -p "请输入循环次数: " max_cnt
请输入循环次数: 10
$ cnt=1
$ while [[ $cnt -le $max_cnt ]]; do   echo "循环 '$cnt' 的总次数是 '$max_cnt'" ;   ((cnt++)); done
循环 '1' 的总次数是 '10'
循环 '2' 的总次数是 '10'
循环 '3' 的总次数是 '10'
循环 '4' 的总次数是 '10'
循环 '5' 的总次数是 '10'
循环 '6' 的总次数是 '10'
循环 '7' 的总次数是 '10'
循环 '8' 的总次数是 '10'
循环 '9' 的总次数是 '10'
循环 '10' 的总次数是 '10'

希望这对您有所帮助。

英文:

You can use the read function with the -p option which prints a prompt. The variable at the end will store the user's answer.

Then you set an initial count variable to 1 (or 0) if you prefer.

Then the while loop says "keep looping as long as this thing is true", where "this thing" is the stuff inside the [[ ]]. -le means "less than or equal to".

((cnt++)) means on each loop to increment the cnt variable.

# prompt user for input
read -p "Please enter the number of loops: " max_cnt

# set initial count 
cnt=1

# iterate over the loop and print the value until max_cnt
while [[ $cnt -le $max_cnt ]]; do
  echo "Loop '$cnt' of '$max_cnt'"
  ((cnt++))
done

For example:

$ read -p "Please enter the number of loops: " max_cnt
Please enter the number of loops: 10
$ cnt=1
$ while [[ $cnt -le $max_cnt ]]; do   echo "Loop '$cnt' of '$max_cnt'" ;   ((cnt++)); done
Loop '1' of '10'
Loop '2' of '10'
Loop '3' of '10'
Loop '4' of '10'
Loop '5' of '10'
Loop '6' of '10'
Loop '7' of '10'
Loop '8' of '10'
Loop '9' of '10'
Loop '10' of '10'

huangapple
  • 本文由 发表于 2023年3月9日 14:19:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681040.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定