首页 > 解决方案 > 有没有办法强制 JavaScript 在警告框中返回负值?

问题描述

JavaScript 返回 X - Y ,其中 X 和 Y 是实数,它们的和是负数,而不仅仅是负数。

我尝试过使用 if else 语句

if (Math.sign(function)<0)
else

if 语句只是在值前面有一个“-”来连接数字前面的字符串“减号”字符,而 else 语句只是一个常规打印输出

function velocity_final(initial_velocity, acceleration, time)
{
    var initial_velocity = prompt('Please enter the Initial Velocity in Meters per Second');
    var acceleration = prompt('Please enter the acceleration in Meters per Second Squared');
    var time = prompt('Please enter the time in seconds');
    var final_velocity = initial_velocity + acceleration * time;
    alert('The Final Velocity is '+ final_velocity  + ' Meters Per Second');
}

标签: javascript

解决方案


prompt总是返回一个字符串,而不是一个数字。即使该人输入了一个数字,它也将是一个代表该数字的字符串,而不是数字本身。

您需要将结果prompt转换为一个数字,然后才能对其进行加法运算。与字符串一起使用时,+是连接运算符,而不是加法运算符。

有点令人困惑的是,您实际上可以+为此目的使用一元。

var initial_velocity = +prompt('Please enter the Initial Velocity in Meters per Second');
var acceleration = +prompt('Please enter the acceleration in Meters per Second Squared');
var time = +prompt('Please enter the time in seconds');
var final_velocity = initial_velocity + acceleration * time;
alert('The Final Velocity is '+ final_velocity  + ' Meters Per Second');

推荐阅读