Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
766 views
in Technique[技术] by (71.8m points)

c - Inputting float into a program that only deals with ints

I have a program, but when I input float numbers whenever the program asks for inputs, the program abruptly skips a step and moves onto the end output. The program is below:

#include <stdio.h>
#include <stdlib.h>

int main()
{
  int a,b,c;
  int i;

  printf("Please enter a number: ");
  scanf("%d", &a);
  printf("Please enter a number: ");
  scanf("%d", &b);

  c = 0; 
  for(i=0; i < b; i++)
    {
    c = c + a;
    } 

  printf("%d x %d = %d
", a, b, c);

  return 0;
}

When I input an int for a, and a float for b, the program will output the product as expected if the numbers after the decimal point for b is truncated. However when I input a float for a, the program doesn't take the value for the second number b and instead skips that step and outputs the integer version of a x -858993460 = 0.

For example:

a = int, b = float

Please enter a number: 3
Please enter a number: 5.6
3 x 5 = 15

a = float, b = skipped

Please enter a number 3.9
Please enter a number: 3 x -858993460 = 0

All the flaws in the code are deliberate, but I just wanted to know why it behaves the way I explained above. I know it's because of something to do with trying to input a float into a signed integer but I'm not sure what exactly is causing it to skip the second scanf("%d", &b). Can anyone explain why this happens?

Thanks.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It looks like scanf() is reading your "3" in the second case, and ignoring the "9".

Then when the second scanf() is called, there is already text in the input buffer (the ".9").

I can't tell exactly what it's doing with the ".9". It may have found the dot and just aborted there with b uninitialized. It should be a simple matter to determine what is happening by stepping through with the debugger.

But, basically, not all the input is being processed by the first call to scanf() and so that's what the second call is trying to read. And that's why it's not waiting for you to input any data for the second call.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...