gpt4 book ai didi

c - 为什么我的代码没有以浮点形式打印答案?

转载 作者:行者123 更新时间:2023-11-30 21:12:36 24 4
gpt4 key购买 nike

#include <stdio.h>
float div ( int a,int b, int c, float x );
int main()
{
int a,b,c,x;
a=250;
b=85;
c=25;

x=div (a,b,c,x);


printf("%d ", x);

}
// your code goes here
float div (int a,int b, int c, float x)
{
x=((a-b)/c);
return(x);

}

最佳答案

因为x被声明为int而不是float

您的代码:

int x;
...
printf("%d ", x);

您需要什么:

float x;
...
printf("%f ", x);

你的 div 函数也是错误的:

float div (int a,int b, int c, float x) 
{
x=((a-b)/c); // << this will perform an integer division
return(x); // and therefore x will be truncated, even if it is a float
}

你需要这个:

float div (int a,int b, int c, float x) 
{
x = ( ((float)(a-b) ) / c);
return x;
}

(a-b) 之前的 (float) 称为强制转换,并确保 (a-b) 将被视为 >float 除以 c 时的数字。

顺便说一句,功能可以简化,你不需要 x 参数:

float div (int a,int b, int c) 
{
float x = ( ((float)(a-b) ) / c);
return x;
}

或者更简单:

float div (int a,int b, int c) 
{
return ((float)(a-b) ) / c;
}

关于c - 为什么我的代码没有以浮点形式打印答案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45631328/

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