包含结构的代码有问题,但我不知道为啥(C)

Posted

技术标签:

【中文标题】包含结构的代码有问题,但我不知道为啥(C)【英文标题】: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?无论如何,非常感谢! 【参考方案1】:

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

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

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

【讨论】:

以上是关于包含结构的代码有问题,但我不知道为啥(C)的主要内容,如果未能解决你的问题,请参考以下文章

我在 csound 中收到一条错误消息,但我不知道为啥

我的 WindowsForm 只是忽略了一些代码行,我不知道为啥?

***Error,我不知道为啥

使用 WPF MVVM 过滤数据网格,它可以工作,但我不知道为啥

表单字段被拒绝,我不知道为啥

我的应用程序不断崩溃,但我不知道为啥