【问题标题】:Store values in struct's fields将值存储在结构的字段中
【发布时间】:2020-07-15 17:33:42
【问题描述】:

我需要一些帮助来保存结构字段中的输入。我希望将两个值存储在两个字段中,并从之前初始化的结构的其他两个字段中减去它们:

...
typedef struct GPS GPS;

struct GPS  {
    float latitude;
    float longitude;
};
...
printf("Enter the location's latitude of a place you want to visit: ");
visitLocation.latitude = scanf("%f", &visitLocation.latitude);
printf("Enter the location's longitude of a place you want to visit: ");
visitLocation.longitude = scanf("%f", &visitLocation.longitude);    
...

我无法让它在这些字段上存储值,有人可以帮我吗?

【问题讨论】:

    标签: c input struct


    【解决方案1】:

    您正在覆盖存储的值。默认情况下,scanf 将读取的值存储在第二个参数的位置。所以你不需要将它分配给同一个变量,因为scanf返回读取的项目数,所以如果你的输入是数字112,scanf返回1并将它分配给visitLocation.latitude,它会覆盖真实的输入。

    你只需要这样做

    printf("Enter the location's latitude of a place you want to visit: ");
    scanf("%f", &visitLocation.latitude);
    printf("Enter the location's longitude of a place you want to visit: ");
    scanf("%f", &visitLocation.longitude); 
    

    它应该工作。祝你好运!

    【讨论】:

    • 确实如此!非常感谢!
    【解决方案2】:

    假设您为 3 个变量调用 scanf(),您希望它返回什么?

    那么让我们检查一下scanf() 的规范:

    RETURN VALUE
           On success, these functions return the number of input items successfully matched and assigned; this can be fewer than provided for, or even zero, in the event of an early matching failure.
    

    在你的情况下,我会这样实现:

    int r;
    r = scanf("%f", &visitLocation.latitude);
    if (1 !=r)
    {
        printf("latitude should be float.\n");
    }
    ...
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多