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

此代码只打印高度单位,而不打印重量单位。我能做什么来修理它?

最佳答案

你不能给这两个字符串留出太多空间:每个字符串只有2char。请注意,C字符串还需要一个空终止字符的空格来标记字符串的结尾。
对于以空结尾的字符,两个字符串只能正确地容纳一个字符。当您输入例如“lb”和“ft”时,您使用的数据超出了数组的范围。将数组的大小更改为(至少)3,并查看代码是否正确打印出这两个单元:

char wunit[3]; // weight unit
char hunit[3]; // height unit

你的代码对我来说在更大的数组中工作得很好。

10-06 05:26
查看更多