四舍五入到小数点后一位的功能测试即使答案正确也显示错误?
Function test with rounding to one decimal place showing error even with correct answers?
我的功能是输入华氏度并输出转换为摄氏度或输入摄氏度并输出转换为华氏度。我的测试挑战是将任何结果四舍五入到第一位小数,我已经正确完成了。但是我的测试另有说明,我正在使用 'Jasmine' 来测试代码。这是我得到的。
const ftoc = function(fahr) {
let input = fahr;
if (typeof fahr === 'number'){
let result = (fahr - 32) * 5/9;
if (Number.isInteger(result) === false) {
return result.toFixed(1);
} else {return result}
}
}
const ctof = function(celc) {
let input = celc;
if (typeof input === 'number') {
let result = celc * (9/5) + 32;
if (Number.isInteger(result) === false) {
return result.toFixed(1);
} else {return result}
}
}
module.exports = {
ftoc,
ctof
}
这是测试
const {ftoc, ctof} = require('./tempConversion')
describe('ftoc', function() {
it('works', function() {
expect(ftoc(32)).toEqual(0);
});
it('rounds to 1 decimal', function() {
expect(ftoc(100)).toEqual(37.8);
});
it('works with negatives', function() {
expect(ftoc(-100)).toEqual(-73.3);
});
});
describe('ctof', function() {
it('works', function() {
expect(ctof(0)).toEqual(32);
});
it('rounds to 1 decimal', function() {
expect(ctof(73.2)).toEqual(163.8);
});
it('works with negatives', function() {
expect(ctof(-10)).toEqual(14);
});
});
我的错误如下:
预期“163.8”等于 163.8。
预期“37.8”等于 37.8。
预期“-73.3”等于 73.3。
似乎期待在数值结果之后有某种额外的时间,但我不确定为什么会这样。谢谢!
您的函数正在返回 string
,因此只需将您的 expect
更新为:
expect(ftoc(100)).toEqual("37.8");
它会起作用。
原因是因为 .toFixed
returns 一个 string
默认情况下,如记录 here.
我的功能是输入华氏度并输出转换为摄氏度或输入摄氏度并输出转换为华氏度。我的测试挑战是将任何结果四舍五入到第一位小数,我已经正确完成了。但是我的测试另有说明,我正在使用 'Jasmine' 来测试代码。这是我得到的。
const ftoc = function(fahr) {
let input = fahr;
if (typeof fahr === 'number'){
let result = (fahr - 32) * 5/9;
if (Number.isInteger(result) === false) {
return result.toFixed(1);
} else {return result}
}
}
const ctof = function(celc) {
let input = celc;
if (typeof input === 'number') {
let result = celc * (9/5) + 32;
if (Number.isInteger(result) === false) {
return result.toFixed(1);
} else {return result}
}
}
module.exports = {
ftoc,
ctof
}
这是测试
const {ftoc, ctof} = require('./tempConversion')
describe('ftoc', function() {
it('works', function() {
expect(ftoc(32)).toEqual(0);
});
it('rounds to 1 decimal', function() {
expect(ftoc(100)).toEqual(37.8);
});
it('works with negatives', function() {
expect(ftoc(-100)).toEqual(-73.3);
});
});
describe('ctof', function() {
it('works', function() {
expect(ctof(0)).toEqual(32);
});
it('rounds to 1 decimal', function() {
expect(ctof(73.2)).toEqual(163.8);
});
it('works with negatives', function() {
expect(ctof(-10)).toEqual(14);
});
});
我的错误如下: 预期“163.8”等于 163.8。 预期“37.8”等于 37.8。 预期“-73.3”等于 73.3。
似乎期待在数值结果之后有某种额外的时间,但我不确定为什么会这样。谢谢!
您的函数正在返回 string
,因此只需将您的 expect
更新为:
expect(ftoc(100)).toEqual("37.8");
它会起作用。
原因是因为 .toFixed
returns 一个 string
默认情况下,如记录 here.