How can we add and print the sum of scores in the C language?

To achieve the functionality of calculating and outputting the sum of scores, you can write a C program using the following steps:

  1. Define a struct to represent a fraction, including two member variables for the numerator and denominator.
  2. Write a function to find the sum of two fractions, first find their least common multiple, then add the two fractions and simplify them.
  3. Input two fractions in the main function, call the sum function, and output the result.

Here is a simple example code:

#include <stdio.h>

// 定义分数结构体
struct Fraction {
    int numerator;
    int denominator;
};

// 求两个分数的和
struct Fraction addFraction(struct Fraction f1, struct Fraction f2) {
    struct Fraction result;
    result.numerator = f1.numerator * f2.denominator + f2.numerator * f1.denominator;
    result.denominator = f1.denominator * f2.denominator;
    
    // 化简分数
    int a = result.numerator, b = result.denominator;
    while (b != 0) {
        int temp = b;
        b = a % b;
        a = temp;
    }
    result.numerator /= a;
    result.denominator /= a;
    
    return result;
}

int main() {
    struct Fraction f1, f2, sum;
    
    // 输入两个分数
    printf("Enter the first fraction (numerator/denominator): ");
    scanf("%d/%d", &f1.numerator, &f1.denominator);
    
    printf("Enter the second fraction (numerator/denominator): ");
    scanf("%d/%d", &f2.numerator, &f2.denominator);
    
    // 求和并输出结果
    sum = addFraction(f1, f2);
    printf("The sum is %d/%d\n", sum.numerator, sum.denominator);
    
    return 0;
}

Through this program, users can input two scores, and the program will calculate their sum and output the result.

bannerAds