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

C语言调用print_array报错:将float[4]传递给类型不兼容的float参数

错误原因

你定义的print_array函数第一个参数为单个float类型变量,但实际调用时传入的是float类型数组,二者类型不匹配,因此触发编译报错。

修正步骤
  • 修改print_array的函数声明,将第一个参数调整为float数组类型,和入参类型匹配
  • 同步修改print_array的函数定义头部,和声明保持一致
  • 在print_array内部新增循环逻辑,遍历数组所有元素,按要求保留两位小数格式化输出,元素之间用, 分隔
修正后完整代码
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>

int times_two(int a);
void print_int(int a);
int half(int a);
void print_float(float a);
void max(float a);
float average(float a);
// 修改了print_array的第一个参数类型为float数组
void print_array(float a[], int b);


int main (void)
{
    int z = get_int("First Value for exercise 3? ");
    int g = get_int("Second Value for exercise 3? ");
    int max_value_1 = get_int("First Value (max) for exercise 4? ");
    int max_value_2 = get_int("Second Value (max for exercise 4? ");
    int x = 2;
    int y = half(x);
    float q = average(z + g);
    print_int(y);
    print_float(2.7444);
    print_float(q);
    if(max_value_1 > max_value_2 || max_value_1 == max_value_2)
    {
        max(max_value_1);
    }
    else
    {
        max(max_value_2);
    }
    float a[] = {1.555, 3, 1.645, 178};
    print_array(a, 4);
}
float average(float a)
{
    return a / 2;
}

int times_two(int a)
{
    return a * 2;
}

int half(int a)
{
    return a / 2;
}

void print_int(int a)
{
    printf("Value Exercise 1 = %i\n", a);
}

void print_float(float a)
{
    printf("Value Exercise 2/3 = %.2f\n", a);
}

void max(float a)
{
    printf("Value Exercise 4 = %.2f\n", a);
}

// 重写print_array函数实现
void print_array(float a[], int b)
{
    printf("Value Exercise 5 = ");
    for (int i = 0; i < b; i++)
    {
        if (i != 0)
        {
            printf(", ");
        }
        printf("%.2f", a[i]);
    }
    printf("\n");
}

运行上述代码传入示例数组{1.555, 3, 1.645, 178}时,输出结果和你预期的一致:

1.55, 3.00, 1.64, 178.00

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 06:45:04