你好,我遇到了这个功能的问题。我想创建一个函数,它接受一个数字,一个起点和一个终点,然后写出从起点到终点的数字乘法表。例如,tabmul(10,2,4)返回
10.2 = 20
10.3 = 30
10.4 = 40
这一切都很好,但它对负数并不起作用。例如, tabmul(10,-4,-1)应生成
10.-4 = -40
10.-3 = -30
10.-2 = -20
10.-1 = -10
但它没有返回任何东西。这是我的代码:
function tabmul(a,b,c){ \\function that generates the multiplication table
var myarray = new Array();
var x
for(x=b; x<=c; x++){
myarray[x - b] = a*x;
document.write(a + "." + x + "=" + myarray[x - b] + "<br>")
}
}
var a = prompt("Enter the number whose table you want to calculate: ","");
var b = prompt("Enter the place where you want the table to start","");
var c = prompt("Enter the place where you want the table to end","");
\\ this checks if the starting point is smaller or equal than the ending point of the table
if (0 <= c-b) {
tabmul(a,b,c);
} else {
alert("The starting point is bigger than the ending point");
}
答案 0 :(得分:0)
您正在比较字符串。这是因为提示返回字符串。您需要将a,b,c
转换为数字。此外,您使用错误的符号进行评论,您需要更正这些符号。
function tabmul(a,b,c){ //function that generates the multiplication table
a = Number(a);
b = Number(b);
c = Number(c);
var myarray = new Array();
var x
for(x=b;x<=c;x++){
myarray[x-b] = a*x;
document.write(a+"."+x+"="+myarray[x-b]+"<br/>")
}
}
var a = prompt("Enter the number whose table you want to calculate: ","");
var b = prompt("Enter the place where you want the table to start","");
var c = prompt("Enter the place where you want the table to end","");
if(0 <= c-b){ //this checks if the starting point is smaller or equal than the ending point of the table
tabmul(a,b,c);
}
else{
alert("The starting point is bigger than the ending point");
}
答案 1 :(得分:0)
您还应该使用Number
或parseInt
将输入转换为数字,以确保其为数字。
之后,您可能会遇到使用负数引用索引数组的问题。
myarray[x-b] // can fail if x-b<0. Also for a large number n it will insert empty elements in your array up to N.
例如,请采取以下措施:
var myarray= new Array();
myarray[-4]=1;
console.log(JSON.stringify(myarray));
// result "[]"
myarray= new Array();
myarray[10]=1;
console.log(JSON.stringify(myarray));
// result "[null,null,null,null,null,null,null,null,null,null,1]"
您可以将其转换为字符串:
myarray['"' + (x-b) + '"'] = a*x;
或者您可以使用push(),索引将从零开始。:
for(x=b;x<=c;x++){
myarray.push(a*x);
document.write(a+"."+x+"="+myarray(myarray.length-1)+"<br/>")
}
答案 2 :(得分:0)
1)为函数参数设置正常名称 2)使用缩进和&#39;让&#39;在&#39;为&#39;循环而不是&#39; var&#39;就在之前:
for(let x = b; x <= c; x++){}
3)不要忘记分号。
function multiplication(val, start, end) {
if(end - start <= 0) return;
for(let i = start; i <= end; i++) {
console.log(val + ' * ' + i + ' = ' + val * i);
}
}
multiplication(10, -4, -1);
10 * -4 = -40
10 * -3 = -30
10 * -2 = -20
10 * -1 = -10