【问题标题】:incompatible type in assignement赋值类型不兼容
【发布时间】:2016-01-14 12:13:04
【问题描述】:

我正在尝试打乱一组数组并按打乱顺序打印它们,但我得到了error: incompatible types when assigning to type 'int' from type 'IRIS',但我无法克服它。

我是一名初级程序员(过去一周刚为大学考试学习了一些基本的 C 语言)。

这是我的代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#define MAX_SAMPLES 5
#define OUTPUT 3
typedef struct {
  double sepal_lenght;
  double sepal_width;
  double petal_lenght;
  double petal_width;
  double out[OUTPUT];
}IRIS;
IRIS samples[MAX_SAMPLES] = {
{5.1,2.5,3.0,1.1,{0.0,1.0,0.0}},
{6.7,3.1,5.6,2.4,{1.0,0.0,0.0}},
{6.4,3.1,5.5,1.8,{1.0,0.0,0.0}},
{7.6,3.0,6.6,2.1,{1.0,0.0,0.0}},
{7.7,2.8,6.7,2.0,{1.0,0.0,0.0}},
};
main (){
int i, temp, randomIndex;
srand(time(NULL));
  for ( i=1; i < MAX_SAMPLES; i++) {
   temp = samples[i];
   randomIndex = rand() %MAX_SAMPLES;
   samples[i] = samples[randomIndex];
   samples[randomIndex] = temp;
}
for ( i=0; i<MAX_SAMPLES; i++) {
  printf("%d\n", samples[i]);
}
}

行错误:temp = samples[i];

非常感谢任何帮助!

【问题讨论】:

  • 您将int 分配给IRIS,这是不兼容的类型。就是这样。
  • tempint 类型; samples[i] 的类型为 IRIS
  • lenght 应该是 length

标签: c incomplete-type


【解决方案1】:

在循环之前从ints 列表中删除temp,然后更改:

temp = samples[i];

到:

const IRIS temp = samples[i];

您不能将IRIS 类型的值分配给int

【讨论】:

  • 非常感谢!这解决了它! (我学到了一些新东西)
【解决方案2】:

您正在声明一个 IRIS 类型的数组,但在您的 for 循环中您使用的是 %d,它仅用于将 int 显示到 printf 中。 如果要显示结构 IRIS 中的数据,则必须访问要显示的属性,而不是结构本身。 例如:

printf("%f\n", samples[i].sepal_lenght);

【讨论】:

  • 非常感谢!你的建议很有用!
【解决方案3】:

您的tempint 类型,而samplesIRIS 的数组,因此您需要将temp 设为IRIS,然后将samples[i] 的所有内容复制到其中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 1970-01-01
    • 2012-09-02
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 2012-06-09
    相关资源
    最近更新 更多