[英]what should i change in my function so it calculates real numbers?
i am trying to write a function that repeatedly adds 0.001 to 't' and then plugs it into 'y' until 't' reaches 0.3 however the numbers come out wrong, but i've noticed that if i change float to int and change the numbers to integer, the fuction works.. what should i change so the function works properly我正在尝试编写一个函数,该函数反复将 0.001 添加到“t”,然后将其插入“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;
}
i've noticed that if i change float to int and change the numbers to integer, the fuction works.. what should i change so the function works properly我注意到,如果我将 float 更改为 int 并将数字更改为 integer,则该功能有效.. 我应该更改什么才能使该功能正常工作
as said in a remark the problem is the way you (try to) print the value in正如在评论中所说,问题是您(尝试)打印值的方式
printf("y is %d when t is 0.3\\n" , y);
%d
suppose the corresponding argument is an int and prints it as an int , but y is a float . %d
假设相应的参数是int并将其打印为int ,但y是float 。 Note that there is no conversion from float to int in that case because the arguments are managed through a varargs请注意,在这种情况下没有从float到int 的转换,因为参数是通过varargs管理的
just do做就是了
printf("y is %f when t is 0.3\n" , y);
Also change也变
void main(void)
to到
int main()
After the changes, compilation and execution :修改后编译执行:
/tmp % gcc -pedantic -Wall -Wextra f.c -lm
/tmp % ./a.out
y is 1.273792 when t is 0.3
Note that all the calculations are done in double , so better to replace float to double to type your vars请注意,所有计算都是在double中完成的,因此最好将float替换为double以键入您的 vars
(edit) Compiling your initial code with gcc and the option -Wall
signals your problems : (编辑)使用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
To use both -Wall and -Wextra is the better option同时使用 -Wall 和 -Wextra 是更好的选择
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.