我正在尝试编写一个函数,反复向“ t”添加0.001,然后将其插入“ y”,直到“ t”达到0.3,但是数字出现错误,但是我注意到,如果我将float更改为int并进行更改将数字转换为整数,函数起作用..我应该更改什么,以便函数正常工作

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

void main(void)
{
    float t,y,dt;

    dt = 0.001;
    y = 1;
    t = 0;

    while (t <= 0.3)
    {
        y = y + dt*(sin(y)+(t)*(t)*(t));
        t = t + dt;
    }

    printf("y is %d when t is 0.3\n" , y);
    return 0;
}

最佳答案

我注意到,如果我将float更改为int并将数字更改为整数,则该函数有效..我应该更改什么,以便该函数正常工作


如评论中所说,问题是您(尝试)打印值的方式


printf("y is %d when t is 0.3\n" , y);



%d假定相应的参数为int并将其打印为int,但y为浮点数。注意,在这种情况下,没有从float到int的转换,因为参数是通过varargs管理的

做就是了

 printf("y is %f when t is 0.3\n" , y);


也改变


void main(void)





int main()


更改后,编译并执行:

/tmp % gcc -pedantic -Wall -Wextra f.c -lm
/tmp % ./a.out
y is 1.273792 when t is 0.3




请注意,所有计算均以double进行,因此最好将float替换为double以键入vars



(编辑)使用gcc编译您的初始代码,选项-Wall表示您的问题:

/tmp % gcc -Wall f.c -lm
f.c:4: warning: return type of 'main' is not 'int'
f.c: In function 'main':
f.c:18: warning: format '%d' expects type 'int', but argument 2 has type 'double'
f.c:19: warning: 'return' with a value, in function returning void


同时使用-Wall和-Wextra是更好的选择

10-08 08:18
查看更多