是否可以在结构中存储多个值?
is it possible to store several values in a structure?
我是 c 的新手,我想知道是否可以在结构中存储许多值? .我想存储 x1、y1、x2、y2 的 1 个以上的值。然后我想要一个随机值 x1,y1,x2,y2。使用结构是否可行,或者我需要使用其他工具?
struct test
{
int x1;
int y1;
int x2;
int y2;
};
看来你需要一个数组。
#include <time.h> //you need this to use time(NULL)
#include <stdlib.h> //you need this for random numbers functions
#include <stdio.h> //you need this for printf
//this is called a macro, it will get replaced by value 10 everywhere in the following code
#define NUM_OF_VALUES 10
struct test
{
int x1[NUM_OF_VALUES];
int y1[NUM_OF_VALUES];
int x2[NUM_OF_VALUES];
int y2[NUM_OF_VALUES];
}
int main() {
struct test my_test = { /* learn about initializes */ };
srand(time(NULL)); //this is how you initialize random number generator to be different every time you run your code
printf("Random value from x1 %d\n", my_test.x1[rand() % NUM_OF_VALUES]);
printf("Random value from y1 %d\n", my_test.y1[rand() % NUM_OF_VALUES]);
return 0;
}
阅读此处了解如何手动在此 struct
中输入一些值以进行测试:https://en.cppreference.com/w/c/language/struct_initialization
我是 c 的新手,我想知道是否可以在结构中存储许多值? .我想存储 x1、y1、x2、y2 的 1 个以上的值。然后我想要一个随机值 x1,y1,x2,y2。使用结构是否可行,或者我需要使用其他工具?
struct test
{
int x1;
int y1;
int x2;
int y2;
};
看来你需要一个数组。
#include <time.h> //you need this to use time(NULL)
#include <stdlib.h> //you need this for random numbers functions
#include <stdio.h> //you need this for printf
//this is called a macro, it will get replaced by value 10 everywhere in the following code
#define NUM_OF_VALUES 10
struct test
{
int x1[NUM_OF_VALUES];
int y1[NUM_OF_VALUES];
int x2[NUM_OF_VALUES];
int y2[NUM_OF_VALUES];
}
int main() {
struct test my_test = { /* learn about initializes */ };
srand(time(NULL)); //this is how you initialize random number generator to be different every time you run your code
printf("Random value from x1 %d\n", my_test.x1[rand() % NUM_OF_VALUES]);
printf("Random value from y1 %d\n", my_test.y1[rand() % NUM_OF_VALUES]);
return 0;
}
阅读此处了解如何手动在此 struct
中输入一些值以进行测试:https://en.cppreference.com/w/c/language/struct_initialization