gpt4 book ai didi

javascript - 关于给定负数将函数返回为 'undefined' 的问题?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:20:30 24 4
gpt4 key购买 nike

如果给定一个负数,我正在尝试编写将返回 undefined 的代码

我被要求使用 Javascript 中的函数计算矩形、三 Angular 形和圆形的面积。我做对了那部分,但问题还说“如果任何参数为负,函数应返回未定义。

function calculateRectangleArea (length, width) {
return length * width;
}
function calculateTriangleArea (base, height) {
return (base * height)/2;
}
function calculateCircleArea (radius) {
return radius * radius * Math.PI;
}

我可以很好地计算面积,但如果有一个负数来得到 undefined,我不知道该写什么。是不是像这样:

if (calculateRectangleArea <0) 
return "undefined";

最佳答案

您需要在 if 语句中测试每个参数以确保它不是负数,如果有任何一个是负数,则返回 undefined - 否则,返回普通计算就像你已经在做的那样:

function calculateRectangleArea(length, width) {
if (length < 0 || width < 0) {
return undefined;
} else {
return length * width;
}
}
function calculateTriangleArea(base, height) {
if (base < 0 || height < 0) {
return undefined;
} else {
return (base * height) / 2;
}
}
function calculateCircleArea(radius) {
if (radius < 0) {
return undefined;
} else {
return radius * radius * Math.PI;
}
}

或者,由于当没有返回值时,默认返回undefined,您也可以只返回所有参数都为非负数的计算,例如:

function calculateRectangleArea(length, width) {
if (length >= 0 && width >= 0) {
return length * width;
}
}

关于javascript - 关于给定负数将函数返回为 'undefined' 的问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54738128/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com