要實現分數求和并輸出的功能,可以通過以下步驟來編寫C語言程序:
以下是一個簡單的示例代碼:
#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;
}
通過這個程序,用戶可以輸入兩個分數,程序將會計算它們的和并輸出結果。