gpt4 book ai didi

c - 你知道为什么 BMI 值的输出总是 0.0000 吗?

转载 作者:行者123 更新时间:2023-12-05 08:21:39 24 4
gpt4 key购买 nike

这是我的代码。无论我输入什么体重和高度,它总是输出 0.0000000。我不确定它有什么问题。

#include <stdio.h>
#include <math.h>


double bmi(w,h){
double bmi = w/h;
return bmi;


}

int main() {

double height;
double weight;
printf("Enter your height in meters: ");
scanf("%lf", &height);
height = pow(height, 2);
printf("Enter your weight in kilograms: ");
scanf("%lf", &weight);


printf("Your BMI is %f\n", bmi(weight, height));



return 0;

}

最佳答案

您使用的是旧式函数定义,未指定参数类型。这导致参数具有 int 类型,这反过来意味着您正在执行整数除法。

这实际上是undefined behavior .因为函数没有指定参数的类型,所以函数定义没有也指定了函数的原型(prototype)。

C standard 的第 6.9.1p7 节关于函数定义状态:

The declarator in a function definition specifies the name of thefunction being defined and the identifiers of its parameters. If thedeclarator includes a parameter type list, the list also specifies thetypes of all the parameters; such a declarator also serves as afunction prototype for later calls to the same function in the sametranslation unit. If the declarator includes an identifier list, 163)the types of the parameters shall be declared in a followingdeclaration list. In either case, the type of each parameter isadjusted as described in 6.7.6.3 for a parameter type list; theresulting type shall be a complete object type.

而且所讨论的定义有一个标识符列表,而不是参数类型列表。

这意味着发生在参数上的唯一转换是默认参数提升,它只是整数提升和floatdouble 的转换.结果是传递的参数类型(即 double)与预期的参数类型(即 int)不兼容,从而触发未定义的行为。

这在第 6.5.2.2p6 节中关于函数调用有详细说明:

If the expression that denotes the called function has a type thatdoes not include a prototype, the integer promotions are performed oneach argument, and arguments that have type float are promoted todouble. These are called the default argument promotions. If thenumber of arguments does not equal the number of parameters, thebehavior is undefined. If the function is defined with a type thatincludes a prototype, and either the prototype ends with an ellipsis (, ...) or the types of the arguments after promotion are notcompatible with the types of the parameters, the behavior isundefined. If the function is defined with a type that does notinclude a prototype, and the types of the arguments after promotionare not compatible with those of the parameters after promotion, thebehavior is undefined, except for the following cases: ... [ not applicable]

您需要显式设置参数的类型:

double bmi(double w, double h){ 
double bmi = w/h;
return bmi;
}

关于c - 你知道为什么 BMI 值的输出总是 0.0000 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71581148/

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