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

将float数组改为double数组后输入值全部为0的问题求助

问题:float数组转double后输入值全部读为0

将C程序中的float array[][]改为double array[][]以提升精度后,输入的值无法被正确读取,所有元素都显示为0.0000000;而使用float类型时输入5能正常显示5.000000。

问题根源

核心原因是格式化输入输出的格式符与数据类型不匹配:

  • 处理float类型时,scanf用%f是正确的
  • 处理double类型时,scanf必须使用%lf格式符(printf中%f和%lf都可以兼容double,但scanf严格区分)

如果用%f读取double变量,会导致内存解析错误,最终读取到错误的0值。

修正后的代码

#include <stdio.h>
#include <math.h>
int main() {
    int limestone, min=0;
    // 输入石灰岩数量(数组行数)
    printf("Enter number of limestone: ");
    scanf("%d", &limestone);
    double array[limestone][3]; // 改为double类型
    // 输入数据
    for(int i=0;i<limestone;i++)
    {
        printf("Enter the %d porosity, hydraulic conductivity (m/s), specific gravity: ", i+1);
        scanf("%lf %lf %lf", &array[i][0], &array[i][1], &array[i][2] ); // 格式符改为%lf
    }
    // 打印数组
    for(int i=0;i<limestone;i++)
    {
        for(int j=0;j<3;j++)
        {
            printf("%f ",array[i][j]); // printf用%f或%lf都可
        }
        printf("\n");
    }
    // 查找比重最小的石灰岩
    for(int i=limestone-1;i>=0;i--)
    {
        if(array[i][2]<array[min][2])
        {
            min=i;
        }
    }
    printf("The limestone with the lowest specific gravity is Limestone %d with a specific gravity of %f",min+1,array[min][2]);
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 09:41:00