C语言中比较两个分数的程序
给定两个分数,分别为分子 nume1 和 nume2,分母为 deno1 和 deno2,任务是比较两个分数,找出较大的一个。例如,我们有一个分数 1/2 和 2/3,较大的一个是 2/3,因为 1/2 的值是 0.5,而 2/3 的值是 0.66667,后者更大。
输入
first.nume = 2, first.deno = 3 second.nume = 4, second.deno = 3
输出
4/3
说明
2/3 = 0.66667 < 4/3 = 1.33333
输入
first.nume = 1, first.deno = 2 second.nume = 4, second.deno = 3
输出
4/3
用于解决该问题的方法如下
//稍后会写
算法
Start
Declare a struct Fraction with elements
nume, deno
In function Fraction greater(Fraction first, Fraction sec)
Step 1→ Declare and Initialize t Y = first.nume * sec.deno - first.deno *
sec.nume
Step 2→ Return (Y > 0) ? first : sec
In function int main()
Step 1→ Declare Fraction first = { 4, 5 }
Step 2→Fraction sec = { 3, 4 }
Step 3→ Fraction res = greater(first, sec)
Step 4→ Print res.nume, res.deno
Stop示例
#include <stdio.h>
struct Fraction {
int nume, deno;
};
// Get max of the two fractions
Fraction greater(Fraction first, Fraction sec){
//check if the result is in negative then the
//second fraction is greater else first is greater
int Y = first.nume * sec.deno - first.deno * sec.nume;
return (Y > 0) ? first : sec;
}
int main(){
Fraction first = { 4, 5 };
Fraction sec = { 3, 4 };
Fraction res = greater(first, sec);
printf("The greater fraction is: %d/%d
", res.nume, res.deno);
return 0;
}输出
如果运行以上代码将生成以下输出 −
The greater fraction is: 4/5
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP