使用 C 中的单元测试进行修正

发布于 2024-10-12 04:57:04 字数 548 浏览 3 评论 0原文

在软件开发人员职位的编程测试中也提出了类似的问题。两天后我仍然没有答案。

假设我们有一个函数,它接受两个浮点数作为输入,并且它没有任何副作用并且确定性地执行(也考虑单线程环境)。例如 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

节枝 2024-10-19 04:57:04

带有 %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.

柠檬 2024-10-19 04:57:04

ab 中的值可能比 printf 打印的值具有更多的有效数字,因此这是一个精度问题。

The values in a and b may have more significant digits than what is printed by printf, thus making this a precision issue.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文