c - 如何在数组中使用类型转换来分隔数据?
问题描述
我想在同一个大小为 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");
}
}
}
解决方案
当您想要将多个不同的数据视为一个单元时,您将使用 astruct
并拥有一个结构数组。
您可以将结构定义为:
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);
}
推荐阅读
- java - Spring R2DBC DatabaseClient 丢失 TZ 信息
- python - 如何在 Python 中创建和使用文本文件?
- android - Android后台进程每分钟从网页加载数据
- python - 在 AWS 中,从 sagemaker 执行笔记本
- asynchronous - 为什么在等待点上持有非发送类型会导致非发送未来?
- android - Trigger scanning on a Zebra TC25 with an Android Delphi application
- python - 从向导按钮 Odoo 更改模型中状态栏的状态
- java - 排序列表
通过优先的起始字母 - r - 使用条件增加数据框的行数
- go - 如何使用收集器跟踪 gRPC 服务(服务器端)