【发布时间】:2021-07-18 10:03:52
【问题描述】:
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdbool.h>
struct game{
bool is_computer_game;
bool is_tabletop_game;
bool is_for_children;
bool is_collective;
};
int main(){
int n,a,b,c,d;
printf("How much games do you want?:");
scanf("%d",&n);
struct game games[n];
for(int i=0;i<n;i++){
a=rand()%2;
b=1-a;
c=rand()%2;
d=rand()%2;
if(a==0){
games[i].is_computer_game=false;
}
if(a==1){
games[i].is_computer_game=true;
}
if(b==0){
games[i].is_tabletop_game=false;
}
if(b==1){
games[i].is_tabletop_game=true;
}
if(c==0){
games[i].is_for_children=false;
}
if(c==1){
games[i].is_for_children=true;
}
if(d==0){
games[i].is_collective=false;
}
if(d==1){
games[i].is_collective=true;
}
}
printf("\nHere is the information about all games we have:\n\n ");
for(int i=0;i<n;i++){
printf("is the game a computer one: %d\n",games[i].is_computer_game);
printf("is the game a tabletop one: %d\n",games[i].is_tabletop_game);
printf("is the game for children: %d\n",games[i].is_for_children);
printf("is the game a collective one: %d\n\n",games[i].is_collective);
}
return 0;
}
好吧,我有这段代码可以创建一个结构并用一些元素填充它并打印所有这些元素。另一件事是该程序还必须打印它的内部供应。长话短说,我需要那个
struct game games[n]
被打印为代码和二进制数字字符串,但我不知道我该怎么做。你能帮帮我吗?
【问题讨论】:
-
您的问题有点不清楚,但如果您只想将
games数组的原始内容打印为十六进制值,您可以执行以下操作:char *ptr = (char*)games; for (int i = 0; i < sizeof(games); ++i) printf(" %02X",ptr[i]); -
顺便说一句,由于 C 中的布尔值只是 0 和 1,因此您的
if语句不是必需的,您可以直接进行赋值,例如games[i].is_computer_game = a; -
SGeorgiades,这个结构只包含零和一,你的建议是真正正确的。谢谢你的帮助