【问题标题】:Confusion regarding a program on structures关于结构程序的困惑
【发布时间】:2017-04-10 13:16:32
【问题描述】:
#include <stdio.h>

main(void)
{
    struct computer
    {
        float cost;
        int year;
        int cpu_speed;
        char cpu_type[16];
    } model;

    printf(“The type of the CPU inside your computer?\n”);
    gets(model.cpu_type);
    printf(“The speed(MHz) of the CPU?\n”);
    scanf(“%d”, &model.cpu_speed);
    printf(“The year your computer was made?\n”);
    scanf(“%d”, &model.year);
    printf(“How much you paid for the computer?\n”);
    scanf(“%f”, &model.cost);

    printf(“Here are what you entered:\n”);
    printf(“Year: %d\n”, model.year);
    printf(“Cost: $%6.2f\n”, model.cost);
    printf(“CPU type: %s\n”, model.cpu_type);
    printf(“CPU speed: %d MHz\n”, model.cpu_speed);

    return 0;
}

以上代码来自Teach Yourself C in 24 hours,但运行时显示杂散错误。

书中还显示了一个输出。

在输出中,模型的成本是$1234.561234.56 怎么能适应 %6.2f... 我的意思是 %6.2f 我们只会得到 234.56,对吧?

【问题讨论】:

标签: c struct structure


【解决方案1】:

双引号 的字符无效,这会导致杂散错误。您可能让他们从其他网站或 pdf 中复制它们。否则你需要检查你的键盘设置。

正确的双引号是"

【讨论】:

  • @ScottHunter 实际错误是this OP 评论
  • @ScottHunter 我实际上已经复制了源代码并编译以查看错误并修复。
【解决方案2】:

%6.2f 中的 6 是最小字段宽度。

【讨论】:

  • 难道不是这样吗——我们先数 6 位,然后倒数 2 位(6.2 中的 2 位),然后再倒数一位小数点? _ _ _ _。 _ _ 所以小数点前3位和小数点后2位???如果不是,我们实际上如何计算这些位??
  • printf 从不截断浮点数的整个部分。 @Susan,请将此作为一个单独的问题提出,您会得到更详细的答案。
【解决方案3】:

你对字符串使用了奇怪的字符:你使用了,但你必须使用"

【讨论】:

    猜你喜欢
    • 2013-12-31
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 2014-11-29
    • 1970-01-01
    • 2018-07-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多