/*展示结构体标签和结构体变量*/
#include <stdio.h>
/*at 结构体标签*/
typedef struct at_tag {
char name[9];
char gender[2];
int age;
};
/*st 结构体变量*/
typedef struct {
char name[9];
char gender[2];
int age;
}st_variate;
void test(void)
{
struct at_tag tag= {
"徐达开",
"M",
24
};
printf("标签结构体:\n");
printf("%s %s %d\n", tag.name, tag.gender, tag.age);
st_variate variate= {
"孙尚香",
"W",
1000
};
printf("结构体变量:\n");
printf("%s %s %d\n", variate.name, variate.gender, variate.age);
}
int main()
{
test();
return 0;
}
//计算3+5,怎么通过结构体指针变量关联add函数,以及通过结构体指针调用add函数输出结果?
#if 1
#include <stdio.h>
#include <stdlib.h>
typedef struct
{
int (*func)(int, int);
int a;
int b;
}func_t;
int add(int a, int b) { return a + b; }
int main()
{
func_t* func1 = (func_t*)malloc(sizeof(func_t));
//计算3+5,怎么通过结构体指针变量关联add函数,以及通过结构体指针调用add函数输出结果?
/*func1->func = add;
int result = func1->func(3, 5);*/
func1[0].func = add;
func1[0].a = 3;
func1[0].b = 5;
int result = func1[0].func(func1[0].a, func1[0].b);
printf("3+5=%d\n", result);
return 0;
}
#endif
/*输入整数为小数点有瑕疵(解决)
* 相较比较完美的代码
*/
#if 1
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
typedef struct st{
int (*fun)(int, int);
char ari[3];
};
int my_Add(int a, int b) { return a + b; }
int my_Sub(int a, int b) { return a - b; }
int my_Mul(int a, int b) { return a * b; }
int my_Div(int a, int b) { return a / b; }
//st* func1 = NULL;
int main()
{
//st * func1 = (st*)malloc(sizeof(st) * 4);
struct st *func1 = malloc( sizeof(struct st));
int a = 0, b = 0;
int scanfResult;
char extreChar;
//double a_input, b_input;
char choice[10];
func1[0].fun = my_Add;
strcpy(func1[0].ari, "add");
func1[1].fun = my_Sub;
strcpy(func1[1].ari, "sub");
func1[2].fun = my_Mul;
strcpy(func1[2].ari, "mul");
func1[3].fun = my_Div;
strcpy(func1[3].ari, "div");
while (1) {
printf("choice arithmetic:add\tsub\tmul\tdiv\n");
scanf("%s", choice);
/* if (choice < 1 || choice >4)
{
printf("input invalid\n");
continue;
}*/
int choice_flag = -1;
for (int i = 0; i < 4; ++i) {
if (strcmp(choice, func1[i].ari) == 0) {
choice_flag = i;
break;
}
}
if (choice_flag == -1) {
printf("arithmetic input invaild\n");
continue;
}
printf("inpout two integer\n");
scanfResult = scanf("%d %d", &a, &b);
if (scanfResult != 2) {
printf("Invalid input. Please enter two integers.\n");
//清楚输入缓冲区中的额外字符
while ((extreChar = getchar()) !='\n' && extreChar != EOF);
continue;
}
int result = func1[choice_flag].fun(a, b);
printf("%s:%d a=%d b=%d\n", func1[choice_flag].ari, result, a, b);
}
free(func1);
return 0;
}
#endif