javascript - 有没有办法强制 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');
}
解决方案
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');
推荐阅读
- c# - 如何检测鼠标是否停止在 Unity 中移动
- java - CSS未在spring boot应用程序中加载
- ruby-on-rails - 无法访问最新版本 GitHub gem 中的功能
- android - 是否可以在 Nativescript 中使用矢量可绘制对象作为图像源?
- javascript - HtmlUnit 执行 Javascript 后如何获取页面
- c# - DrawArc 对圆形有效,但对椭圆无效
- javascript - 在异步调用中使用 Promise 进行递归
- java - hibernate & jpa:具有复合主键的表:自动增量问题
- jquery - Angular6应用程序默认添加jquery
- hadoop - Sqoop 导入具有带 where 子句和并行处理的 SQL 查询