1、基本的数学运算
#include <stdio.h>
int main() {
int a = 10, b = 5;
int sum, difference, product;
float quotient;
sum = a + b;
difference = a - b;
product = a * b;
quotient = (float)a / b;
printf("Sum: %d\n", sum);
printf("Difference: %d\n", difference);
printf("Product: %d\n", product);
printf("Quotient: %.2f\n", quotient);
return 0;
}
2、使用函数封装
#include <stdio.h>
void calculate(int a, int b, int *sum, int *difference, int *product, float *quotient) {
*sum = a + b;
*difference = a - b;
*product = a * b;
*quotient = (float)a / b;
}
int main() {
int a = 10, b = 5;
int sum, difference, product;
float quotient;
calculate(a, b, &sum, &difference, &product, "ient);
// 输出结果
printf("Sum: %d\n", sum);
printf("Difference: %d\n", difference);
printf("Product: %d\n", product);
printf("Quotient: %.2f\n", quotient);
return 0;
}
3、使用宏定义
#include <stdio.h>
#define CALCULATE(a, b, sum, difference, product, quotient) \
do { \
sum = (a) + (b); \
difference = (a) - (b); \
product = (a) * (b); \
quotient = (float)(a) / (b); \
} while(0)
int main() {
int a = 10, b = 5;
int sum, difference, product;
float quotient;
CALCULATE(a, b, sum, difference, product, quotient);
printf("Sum: %d\n", sum);
printf("Difference: %d\n", difference);
printf("Product: %d\n", product);
printf("Quotient: %.2f\n", quotient);
return 0;
}
4、使用数组和循环
#include <stdio.h>
int main() {
int a = 10, b = 5;
int results[4];
results[0] = a + b;
results[1] = a - b;
results[2] = a * b;
results[3] = (float)a / b;
printf("Sum: %d\n", results[0]);
printf("Difference: %d\n", results[1]);
printf("Product: %d\n", results[2]);
printf("Quotient: %.2f\n", (float)results[3]);
return 0;
}
5、使用指针和动态内存分配
#include <stdio.h>
#include <stdlib.h>
void calculate(int a, int b, int *sum, int *difference, int *product, float *quotient) {
*sum = a + b;
*difference = a - b;
*product = a * b;
*quotient = (float)a / b;
}
int main() {
int a = 10, b = 5;
int *results = malloc(4 * sizeof(int));
if (results == NULL) {
printf("Memory allocation failed.\n");
return 1;
}
calculate(a, b, &results[0], &results[1], &results[2], (float *)&results[3]);
printf("Sum: %d\n", results[0]);
printf("Difference: %d\n", results[1]);
printf("Product: %d\n", results[2]);
printf("Quotient: %.2f\n", (float)results[3]);
free(results);
return 0;
}