#include <stdio.h>
#include <math.h>
#include <stdlib.h>
int main(void)
{
char wunit[2]; // weight unit
char hunit[2]; // height unit
double weight, height;
printf("Enter the body weight: ");
scanf("%lf%s", &weight, &wunit); // input weight and unit eg. 150lb
printf("Enter the height: ");
scanf("%lf%s", &height, &hunit); // input height and unit eg. 5.65 ft
printf("The height unit: %s\n", hunit);
printf("The weight unit: %s", wunit);
return 0;
}
这段代码只打印出高度单位,不打印体重单位。我该怎么做才能修复它?
最佳答案
您没有为这两个字符串留出太多空间:每个字符串只有 2 个 char
。请注意,C 字符串还需要空终止字符的空间来标记字符串的结尾。
使用空终止字符,您的两个字符串每个只能正确包含一个字符。当您输入例如“lb”和“ft”,您正在使用数组范围之外的数据。将数组的大小更改为(至少)3,并查看代码是否正确打印出两个单位:
char wunit[3]; // weight unit
char hunit[3]; // height unit
您的代码适用于较大的数组。
关于c - 为什么只打印输入的第二个值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12555405/