变量乘法

编程入门 行业动态 更新时间:2024-10-12 05:45:47
本文介绍了变量乘法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在编写一个脚本,为插入的数字提供阶乘,但是我在乘法时遇到了一些问题.

I'm making a script which gives the factorial for a inserted number, but i'm having some problems with the multiplication.

注意:阶乘为:9!= 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1

Note: the factorial for is given by: 9!=9*8*7*6*5*4*3*2*1

这是我的代码:

#!/bin/bash echo "Insert an Integer" read input if ! [[ "$input" =~ ^[0-9]+$ ]] ; then exec >&2; echo "Error: You didn't enter an integer"; exit 1 fi function factorial { while [ "$input" != 1 ]; do result=$(($result * $input)) input=$(($input-1)) done } factorial echo "The Factorial of " $input "is" $result

对于不同的乘法技术,它总是给我带来各种错误:/

it keeps giving me errors of all kinds for diferent multiplication technics :/

当前输出为:

joaomartinsrei@joaomartinsrei ~/Área de Trabalho/Shell $ ./factorial.sh Insert an Integer 3 ./factorial.sh: line 15: * 3: syntax error: operand expected (error token is "* 3") The factorial of 3 is

非常感谢, 最好的问候

Many Thanks, Best Regards

推荐答案

主要问题是,您永远不会初始化result(至1),因此:

The main problem is that you never initialize result (to 1), so this:

result=$(($result * $input))

等效于此:

result=$(( * $input))

这不是有效的算术表达式.

which is not a valid arithmetic expression.

更多推荐

变量乘法

本文发布于:2023-11-30 13:13:24,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1650108.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:乘法   变量

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!