gpt4 book ai didi

c - 使用 stdbool.h 时的意外编译器行为

转载 作者:太空宇宙 更新时间:2023-11-03 23:53:15 25 4
gpt4 key购买 nike

这是我的代码

主程序

#include <stdio.h>
#include <stdbool.h>
#include "func.h"

int main () {
int counts = 10;
printf("Expected: %lF and rcount %lF,%lF\n",
counts * 30* 0.156, rcount(0,30), rcount(30,0));

return 0;
}

这是我简化的 func.h

#ifndef FUNC_INCLUDED
#define FUNC_INCLUDED

float rcount(int m, int n);

#endif

最后是我的 func.c

#include <stdio.h>
#include <stdbool.h>
#include <math.h>
#include "func.h"

double rcount(int m, int n) {
double series1 = ((double)m/2)*(10+(double)m*10)/20;
double series2 = ((double)n/2)*(10+(double)n*10)/20;
return (series2 > series1) ? series2-series1 : series1-series2;
}

现在,如果我执行,我会得到 rcount() 的随机值,而如果我删除 #include<stdbool.h>从主要方面,我得到了正确的值(value)观。

有什么想法吗?

最佳答案

正如@Carl Norum 所说,“一定有您没有告诉我们的事情”非常有说服力。

rcount() 调用是 printf() 语句返回其 double 类型,但 printf() 由于原型(prototype)而期望 float,如果未看到原型(prototype)则期望 int。在任何一种情况下,printf() 都会显示错误的数据。

尝试 3 件事:1) 使用不同于 FUNC_INCLUDED 的不同定义,稍微可能 stdbool.h 正在使用该宏。 2)更改原型(prototype)和实现以返回相同的类型,最好是 double 。 3) 在 main() 之前直接复制 rcount() 原型(prototype)的冗余副本。

extern double rcount(int m, int n);

stdbool.h 的使用/缺乏是一个转移注意力的问题。有/没有它,你的编译正在使用一些不同的文件、选项等。(除非它是 FUNC_INCLUDED)

关于c - 使用 stdbool.h 时的意外编译器行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14514967/

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