C语言编程题计算两个数的和、差、积、商

C语言中,可以用多种方式来计算两个数的和、差、积和商。不同的方法来实现基本的数学运算,并且涵盖了直接计算、函数封装和宏定义这几种常见的方式。

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;
}

推荐阅读
cjavapy编程之路首页