实验9-9 有理数比较(10 分)
本题要求编写程序,比较两个有理数的大小。
输入格式:
输入在一行中按照“a1/b1 a2/b2”的格式给出两个分数形式的有理数,其中分子和分母全是整形范围内的正整数。
输出格式:
在一行中按照“a1/b1 关系符 a2/b2”的格式输出两个有理数的关系。其中“>”表示“大于”,“<”表示“小于”,“=”表示“等于”。
输入样例1:
1/2 3/4
输出样例1:
1/2 < 3/4
输入样例2:
6/8 3/4
输出样例2:
6/8 = 3/4
#include<stdio.h>
#include<string.h>
//思路:先自定义有理数结构体。主函数中使用scanf读入分子和分母,除号直接输入。
// 比较阶段,方法1:使用强制类型转换将每个式子转换成double类型。
// 方法2:使用交叉相减的思想使用一个变量判断两个分式相减的结果即可。
struct rational_number//自定义数据类型,有理数结构体
{
int FenZi;
int FenMu;
};
int main()
{
struct rational_number n1, n2;
double c1, c2;
int ans; //思路2:可以使用一个变量判断输入的两个分式的大小。
char ch;
scanf("%d/%d%d/%d", &n1.FenZi, &n1.FenMu, &n2.FenZi, &n2.FenMu);
c1 = ((double)n1.FenZi) / n1.FenMu;
c2 = ((double)n2.FenZi) / n2.FenMu;
//ans = n1.FenZi*n2.FenMu - n1.FenMu*n2.FenZi; //思路2
if (c1 > c2)
{
printf("%d/%d > %d/%d\n", n1.FenZi, n1.FenMu, n2.FenZi, n2.FenMu);
}
if (c1 == c2)
{
printf("%d/%d = %d/%d\n", n1.FenZi, n1.FenMu, n2.FenZi, n2.FenMu);
}
if (c1 < c2)
{
printf("%d/%d < %d/%d\n", n1.FenZi, n1.FenMu, n2.FenZi, n2.FenMu);
}
return 0;
}
实验9-9 有理数比较(10 分)
最新推荐文章于 2025-03-18 16:19:17 发布