【问题标题】:Array initialization in C — "cannot convert '<brace-enclosed initializer list>' to 'float' in assignment" errorC 中的数组初始化——“不能在赋值中将 '<brace-enclosed initializer list>' 转换为 'float'”错误
【发布时间】:2017-01-14 20:47:37
【问题描述】:

我正在尝试为我的模拟项目编译代码,并尝试初始化并表示我的 rho 数组,但遇到了初始化程序错误:

无法将“大括号括起来的初始化程序列表”转换为“浮点数” 任务。

我需要将rho[0] 分配给数组的第一个成员,依此类推。

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <math.h>

int main()
{
    float lambda; // ratio of customers and time
    float N; // mean number of customers in the system
    float Q; // mean number of customers in queue
    float res_time; // response time
    float mu; // service rate , assuming mu = 10 customers/s for this assignment
    int i;
    float rho[10]; // array for rho values

    rho[10] = { 0.1, 0.4, 0.5, 0.6, 0.7, 0.74, 0.78, 0.8, 0.85, 0.9 };

    printf("\nPlease enter the mu : ");
    scanf("%f", &mu);

    FILE *f1, *f2, *f3, *f4, *f5, *f6, *f7, *f8, *f9, *f10;

    if (i == 0)
    {
        N = rho[i] / (1 - rho[i]);
        lambda = rho[i] * mu;
        Q = (i * rho[i]) / (1 - rho[i]);
        res_time = N / lambda;
        printf("%.4f \t\t %.4f \t\t %.4f \t\t %.4f \n", rho[i], N, Q, res_time);

        f1 = fopen("NvsRho[0.1].txt", "w");
        if (f1 == NULL)
        { 
            printf("Cannot open file.\n");
            exit(1);
        }

        fprintf(f1, "RHO \t\t N \n--- \t\t ---\n");

        fprintf(f1, "%.4f \t\t %.4f \n", i, N);

        fclose(f1);
    }
    return 0;
}

【问题讨论】:

  • rho[10] 是一个数字而不是一个数组。

标签: c arrays initialization


【解决方案1】:

rho[10] = ...

这不是初始化器。这是一个赋值语句。一个无效的 rho[10] 是一个数组元素。

初始化器非常具体地指代作为变量声明一部分的赋值。所以只需更改为:

float rho[] = { 0.1 , 0.4 , 0.5 , 0.6 , 0.7 , 0.74 , 0.78 , 0.8 , 0.85 , 0.9 } ;

请注意,我还删除了数组大小。最好让编译器为你解决这个问题(除非你想要一个大于初始化元素数量的数组)。

【讨论】:

  • 当我尝试这个时,会打印“[Error] expected primary-expression before ']' token”错误。 @kaylum
  • @erengsgs 请在问题中显示您更新的代码。你可能犯了一个错误。请保留原代码并在其下方添加新代码以保留问题历史记录。
  • 现在我解决了这个问题。非常感谢您的建设性意见。在这个网站上,大多数人不明白,每个人都是代码大师是不可能的。再次感谢你。 @kaylum
  • @erengsgs 的常见做法是接受适合您的答案
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-17
  • 1970-01-01
  • 1970-01-01
  • 2023-02-11
  • 1970-01-01
  • 2016-05-15
  • 1970-01-01
相关资源
最近更新 更多