使用 C 中的单元测试进行修正
在软件开发人员职位的编程测试中也提出了类似的问题。两天后我仍然没有答案。
假设我们有一个函数,它接受两个浮点数作为输入,并且它没有任何副作用并且确定性地执行(也考虑单线程环境)。例如 bool test(float arg1, float arg2);
为了测试它,假设我们使用任意大量的随机输入。该功能很少会失败,但确实会失败。假设我们使用这段代码来测试:
//Set a,b
if(test(a,b)){
printf("Test passed\n");
} else {
printf("%f %f\n", a,b);
}
因此,在捕获打印的输入后,我们使用这些输入,如下所示:
a = //Fill from the printf
b = //Fill from the printf
boolean a = test(a,b);
验证 a 的结果后,测试有效/通过。你有什么解释?我知道用于调试的 printf 可能很棘手,但是......这是我被问到的问题。
A similar question was asked during a programming test for a Software Developer position. After two days I still don't have an answer.
Suppose we have a function that takes two floats as input and it does not have any side effect and executes deterministically (also consider a single-thread environment). E.g. bool test(float arg1, float arg2);
To test it, let's say we use an arbitrary large number of random inputs. The function fails very rarely but it fails. Let's say that we use this piece of code to test:
//Set a,b
if(test(a,b)){
printf("Test passed\n");
} else {
printf("%f %f\n", a,b);
}
So, after capturing the input that was printed, we use those inputs like this :
a = //Fill from the printf
b = //Fill from the printf
boolean a = test(a,b);
After verifying the result of a, the test is valid/passed. What explanation do you have ? I know that printf for debugging can be tricky but... it was the question I was asked.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
带有
%f
说明符的printf
不会打印超过 7 位十进制数字,以避免给人留下比实际更准确的印象。我的猜测是,其中一个输入是这样的,当它通过 printf 打印出来,然后由编译器读回时,结果略有不同。
printf
with the%f
specifier doesn't print more than 7 decimal digits, to avoid giving an impression of greater accuracy than it actually has.My guess would be that one of the inputs is such that when it's printed out via
printf
, and then read back in by the compiler, the result is slightly different.a
和b
中的值可能比printf
打印的值具有更多的有效数字,因此这是一个精度问题。The values in
a
andb
may have more significant digits than what is printed byprintf
, thus making this a precision issue.