简体   繁体   中英

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?

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).

Consequently, your numbers aren't being converted properly to doubles, and you can't expect proper results.

The problem is probably due to scanf. I suggest using fgets instead. 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

#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.

#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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM