【问题标题】:Problem with code including structures but I have no idea why (C)包含结构的代码有问题,但我不知道为什么(C)
【发布时间】:2022-01-08 08:31:24
【问题描述】:

所以,我是一个初学者,我正在学习结构,所以我决定尝试制作一个程序,它采用米和厘米为单位的 2 个距离的长度,但它跳过了获取米值的输入第二距离。我使用的代码是:

#include<stdio.h>

struct distance{
    int meter;
    float centimeter;
}l1,l2,sum;

int main()
{
    printf("Distance 1 : \n");
    printf("Enter the meter value :");
    scanf("%d",&l1.meter);
    printf("Enter the centimeter value :");
    scanf("%.2f",&l1.centimeter);

    printf("Distance 2 : \n");
    printf("Enter the meter value : \n");
    scanf("%d",&l2.meter);
    printf("Enter the centimeter value :");
    scanf("%.2f",&l2.centimeter);



    sum.meter = l1.meter + l2.meter;
    sum.centimeter = l1.centimeter + l2.centimeter;

    while(sum.centimeter >= 100)
    {
        ++sum.meter;
        sum.centimeter-=100;
    }

    printf("The sum of the distances you have entered is %d m and %f cm.",sum.meter,sum.centimeter);
    return 0;

}

我做错了什么?

【问题讨论】:

  • 您没有阅读编译器警告。 %.2f 不是 scanf 的有效格式,请使用 %f
  • 谢谢!我没有看到任何编译器警告,可能是因为我的 IDE?无论如何,非常感谢!

标签: c struct


【解决方案1】:

您在 scanf("%.2f"...) 中使用了无效的格式说明符。相反,您可以使用scanf("%f"...)。但是,也许您想打开编译器警告。这是我在机器上收到的相关警告:

warning: invalid conversion specifier '.' [-Wformat-invalid-specifier]

scanf("%.2f",&l2.centimeter);
        ~^

【讨论】:

    猜你喜欢
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 2019-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    相关资源
    最近更新 更多