You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何使用scanf时出现Segmentation fault (core dumped)错误?

问题分析与修复方案

你的程序触发Segmentation fault的核心原因有两点:

  1. scanf格式符不匹配:针对double类型变量,scanf必须使用%lf格式符,你误用了给float类型用的%f。
  2. 未传递变量地址:scanf的第二个参数需要接收变量的内存地址(指针),你直接传入变量名,导致程序尝试将输入值写入非法内存区域。

修复后的完整代码片段:

#include <stdio.h>
#include <string.h>

int main()
{
    // 定义常量
    const double adultPrice = 10, childPrice = 6;
    const double profitMargin = .2;

    // 定义票房相关变量
    double adultTix, childTix, gross, adultGross, childGross, net, paidToDist;

    // 存储电影名称
    char movieName[50];

    // 获取电影名称
    printf("Please enter the movie name: ");
    scanf("%s", movieName); // 数组名本身就是指针,此处无需加&

    // 获取成人票销量
    printf("Please enter the number of adult tickets sold: ");
    scanf("%lf", &adultTix); // 修正:使用%lf格式符,传递变量地址&adultTix

    // 获取儿童票销量
    printf("Please enter the number of child tickets sold: ");
    scanf("%lf", &childTix); // 同样修正格式符与地址传递

    // 后续计算与输出示例
    adultGross = adultTix * adultPrice;
    childGross = childTix * childPrice;
    gross = adultGross + childGross;
    net = gross * profitMargin;
    paidToDist = gross - net;

    printf("\n=== Box Office Report ===\n");
    printf("Movie Name: %s\n", movieName);
    printf("Adult Tickets Sold: %.0f\n", adultTix);
    printf("Child Tickets Sold: %.0f\n", childTix);
    printf("Gross Revenue: $%.2f\n", gross);
    printf("Net Profit: $%.2f\n", net);
    printf("Amount Paid to Distributor: $%.2f\n", paidToDist);

    return 0;
}

额外提示:

  • 如果电影名称包含空格,%s会在空格处停止读取,建议改用fgets(movieName, sizeof(movieName), stdin)读取完整字符串(注意要手动处理末尾的换行符)。

内容的提问来源于stack exchange,提问作者birchwoody

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 07:25:24