[英]floating point division in C
I am writing a program that needs to do a bit of arithmetic. 我正在编写一个需要做一点算术的程序。
Here's what I have so far: 这是我到目前为止的内容:
#include <stdio.h>
int main(void){
double h, x, n;
printf("enter h > ");
scanf("%1f", &h);
printf("enter x > ");
scanf("%1f", &x);
/* here's where I believe I'm encountering an error */
n = x/h;
return 0;
}
so let's say I put in h = 0.01 with x = 0.25, I should get n = 0.25/0.01 = 25 right? 因此,假设我将h = 0.01放入x = 0.25,我应该得到n = 0.25 / 0.01 = 25对吗?
I've tried typecasting: 我尝试过类型转换:
n = (float)x/(float)h;
but it doesn't work... 但这行不通...
You have written %1f
(that's a digit one) in your scanf calls, but the right format for a double is %lf
(that's a lower case L). 您已经在scanf调用中写入了
%1f
(即数字1),但双%lf
格式的正确格式为%lf
(即小写L)。
Consequently, your numbers aren't being converted properly to doubles, and you can't expect proper results. 因此,您的数字无法正确转换为双精度,也无法期望获得正确的结果。
The problem is probably due to scanf. 该问题可能是由于scanf引起的。 I suggest using fgets instead.
我建议改用fgets。 But try:
但是尝试:
int main(void){
float h, x, n;
printf("enter h > ");
scanf("%f", &h);
getchar();
printf("enter x > ");
getchar();
scanf("%f", &x);
n = x/h;
return 0;
}
The reason is that you have declared h,x,n to be a double and then assigned it to a float.try using float in the variable declaration 原因是您已将h,x,n声明为双精度型,然后将其分配给float.try在变量声明中使用float
#include <stdio.h>
int main(void){
float h, x, n;
printf("enter h > ");
scanf("%f", &h);
printf("enter x > ");
scanf("%f", &x);
n = x/h;
printf("%f",n);
return 0;
} }
See my comment . 看我的评论 。 You need to specify the
l
modifier when attempting to read double
input. 尝试读取
double
输入时,需要指定l
修饰符。
#include <stdio.h>
inline int flush() {
return fflush(stdout);
}
int main() {
double x, h, n;
printf("enter h> ");
flush();
scanf("%lf", &h);
printf("enter x> ");
flush();
scanf("%lf", &x);
n = x / h;
printf("n: %lf\n", n);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.