c语言比较分数大小的代码怎么写
时间: 2023-05-31 10:01:40 浏览: 180
以下是用C语言比较分数大小的代码:
```c
#include <stdio.h>
int main() {
float score1, score2;
printf("请输入第一个分数:");
scanf("%f", &score1);
printf("请输入第二个分数:");
scanf("%f", &score2);
if (score1 > score2) {
printf("第一个分数大于第二个分数\n");
} else if (score1 < score2) {
printf("第一个分数小于第二个分数\n");
} else {
printf("两个分数相等\n");
}
return 0;
}
```
代码说明:
1. 从标准输入读取两个浮点数类型的分数。
2. 使用if-else语句比较两个分数的大小。
3. 根据比较结果输出相应的信息。
相关问题
c语言比较分数大小
在C语言中,可以使用`if`语句或者三目运算符来比较分数大小。以下是两种方法的示例代码:
使用if语句:
```c
#include <stdio.h>
int main() {
float score1 = 76.5;
float score2 = 85.5;
if (score1 > score2) {
printf("score1 is greater than score2\n");
} else if (score1 < score2) {
printf("score2 is greater than score1\n");
} else {
printf("score1 is equal to score2\n");
}
return 0;
}
```
使用三目运算符:
```c
#include <stdio.h>
int main() {
float score1 = 76.5;
float score2 = 85.5;
char* result = (score1 > score2) ? "score1 is greater than score2" : (score1 < score2 ? "score2 is greater than score1" : "score1 is equal to score2");
printf("%s\n", result);
return 0;
}
```
以上两种方法都可以实现比较分数大小的功能。
C语言通分比较分数大小
要比较两个分数的大小,需要将它们通分,然后比较分子的大小。以下是一段 C 语言代码,可以实现通分比较分数大小的功能:
```c
#include <stdio.h>
// 辗转相除法求最大公约数
int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
int main() {
int a1, b1, a2, b2;
printf("请输入两个分数(形如 a/b c/d):");
scanf("%d/%d %d/%d", &a1, &b1, &a2, &b2);
// 通分
int lcm = b1 * b2 / gcd(b1, b2);
a1 = a1 * (lcm / b1);
a2 = a2 * (lcm / b2);
// 比较分子大小
if (a1 > a2) {
printf("第一个分数大于第二个分数\n");
} else if (a1 < a2) {
printf("第一个分数小于第二个分数\n");
} else {
printf("两个分数相等\n");
}
return 0;
}
```
以上代码中,`gcd` 函数使用辗转相除法求两个数的最大公约数。在主函数中,首先读入两个分数,然后求出它们的最小公倍数(即两个分母的乘积除以它们的最大公约数),并将分子通分。最后比较两个分数的分子大小即可。