我不明白为什么不执行要求用户重量输入的最后一行。这可能是记忆问题吗?或者我错误地写了结构?或者我是否错误地写了对scanf()的调用?或者以上所有?
#include <stdio.h>
struct date{
int month;
int day;
int year;
};
struct healthProfile{
char firstName[20];
char lastName[20];
struct date birthday;
float height; //inches
float weight; //pounds
};
int main(void)
{
struct healthProfile patient1;
printf("%s\t", "Please enter the patient's first name:");
scanf("%s", patient1.firstName);
printf("%s\t", "Please enter the patient's last name:");
scanf("%s", patient1.lastName);
printf("%s\t", "Please enter the date of birth(mm/dd/yyyy)");
scanf("%2i/%2i/%4i", &patient1.birthday.month, &patient1.birthday.day, &patient1.birthday.year);
printf("%s\t", "Please enter the patient's height in inches");
scanf("%.2f", &patient1.height);
printf("%s\t", "Please enter the patient's weight in pounds");
scanf("%.2f", &patient1.weight);
return 0;
}
答案 0 :(得分:1)
与printf
不同,scanf
的格式说明符不具有精确性。编译器应该警告你:
x1.c: In function ‘main’:
x1.c:34:3: warning: unknown conversion type character ‘.’ in format [-Wformat=]
scanf("%.2f", &patient1.height);
^
x1.c:34:3: warning: too many arguments for format [-Wformat-extra-args]
x1.c:37:3: warning: unknown conversion type character ‘.’ in format [-Wformat=]
scanf("%.2f", &patient1.weight);
^
x1.c:37:3: warning: too many arguments for format [-Wformat-extra-args]
删除精度,您将能够正确阅读:
printf("%s\t", "Please enter the patient's height in inches");
scanf("%f", &patient1.height);
printf("%s\t", "Please enter the patient's weight in pounds");
scanf("%f", &patient1.weight);
答案 1 :(得分:0)
当您从控制台接收输入时,它是行缓冲的,但%f格式说明符仅提取数字数据,将换行符(至少)保留在缓冲区中。下一个输入将丢弃前导空格(前一个调用的换行符),但是对于您需要的最后一个输入或丢弃它。一种方式:
int c ;
while ((c = getchar()) != '\n' && c != EOF) { }
scanf("%f", &patient1.weight);
然而,在任何不使用换行符的输入之后执行此操作是个好主意,并且在这种情况下更简单地将输入包装在函数中说getfloat()
以减少重复。