我想在同一个大小为 100x4 的数组中添加 2 种不同类型。在第一列中,我想添加食物名称(使用指针),在第二列和第三列中添加一些数字,例如卡路里和进食时间(使用类型转换)。
我已经尝试了很多天,但找不到任何解决方案。有没有办法通过类型转换来解决这个问题?
#include <stdio.h>
int main(){
char *table[100][4];
int n=0;
int j;
for (j=0;j<4;j++){
if (j==0){
printf ("Add your food:\n");
scanf("%c",&table[n][j]);
}else if (j==1){
printf ("Add calories:\n");
(float) *table[n][j];
scanf("%d",&table[n][j]);
}else if (j==2){
(float) *table[n][j];
printf ("Add the time you ate:\n");
scanf("%.2f",&table[n][j]);
}else if (j==3){
printf ("Kati\n");
}
}
for (j=0;j<4;j++){
if (j==0){
printf ("food:%c",&table[n][j]);
}else if (j==1){
(float) *table[n][j];
printf ("calories:%f",*table[n][j]);
}else if (j==2){
(float) *table[n][j];
printf ("time you ate:%f",*table[n][j]);
}else if (j==3){
printf ("Kati\n");
}
}
}
最佳答案
当您想要将多个不同的数据视为一个单元时,您可以使用 struct
并拥有一个结构数组。
您可以将结构定义为:
struct food {
char name[50];
int calories;
float time;
};
并像这样使用它:
struct food table[100];
int n=0;
for (n=0; n<100; n++) {
printf ("Add your food:\n");
scanf("%49s",table[n].name);
printf ("Add calories:\n");
scanf("%d",&table[n].calories);
printf ("Add the time you ate:\n");
scanf("%f",&table[n].time);
}
for (n=0; n<100; n++) {
printf("food:\n");
printf(" name: %s\n", table[n].name);
printf(" calories: %d\n", table[n].calories);
printf(" time: %.2f\n", table[n].time);
}
关于c - 如何通过数组中的类型转换来分离数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54023177/