要实现分数求和并输出的功能,可以通过以下步骤来编写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;
}
通过这个程序,用户可以输入两个分数,程序将会计算它们的和并输出结果。