javascript - 在 For 循环中乘以整数

标签 javascript types type-conversion iteration multiplication

这里是 JavaScript 初学者...

我正在研究 Adrian Neumann 的 Simple Programming Problems我的问题是关于初级练习中的数字 6。

Write a program that asks the user for a number n and gives him the possibility to choose between computing the sum and computing the product of 1,…,n.

// var myArray = []; // for testing
var mySum = 0;
var userNum = prompt("What is your number? ");
var userChoice = prompt("Would you like to add up (+) or multiply (*) all the numbers from 1 to your number? Please enter (+) or (*): ");

if (userChoice == "+") {
    for (var i = userNum; i > 0; i--) {
        mySum += +i;
    }
    console.log("Your answer is " + mySum);
} else if (userChoice == "*") {
    for (var i = userNum; i > 0; i--) {
        mySum *= +i;
        // myArray.push(i); // for testing
    }
    console.log("Your answer is " + mySum);
    // console.log(myArray); // for testing
}

当输入乘法值时,答案总是0。显然,我认为 0 被包含在迭代中,所以我设置了一个空数组 myArray,并使用 myArray.push( i);... 0 从未作为值包含在数组中。

除了一些明显的表单验证注意事项外,任何人都可以告诉我我缺少什么吗?为什么我的答案总是 0

注意:代码的sum 部分似乎运行得非常出色。

请注意,我是 JavaScript 的初学者,所以如果您想发表评论,请告诉我您为什么按照您的方式更改代码,而不是简单地向我吐回代码.这是一个很大的帮助,谢谢。

最佳答案

好吧,您将 mySum 初始化为 0,因此在循环的每次迭代中,您会将 i 乘以零并保存结果(再次为零)回到 mySum。对于乘法,您必须从一开始。

关于javascript - 在 For 循环中乘以整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37968114/

相关文章:

postgresql - 微软十六进制日期

c++ - 如何在 C++ 中返回函数类型以外的数据类型?

javascript - 从 localStorage 中提取数字作为数字

javascript - Safari 在 jQuery 中返回错误的 CSS 值

jquery-ui - 我如何将 @types/jqueryui 与 angular2( typescript )一起使用

haskell - 如何使用函数依赖和存在量化来为我的类型删除不必要的参数

types - 在 Erlang 中编写规范的指南

javascript - 至少包含 1 个数字和 1 个字符且固定长度为 11 的字母数字字符串的正则表达式

c# - 表单提交后启用文本框和按钮 ASP.NET MVC 4

javascript - 公共(public)静态无效oddsToFront(int [] a)