大还是小?
Description
输入两个实数,判断第一个数大,第二个数大还是一样大。每个数的格式为:
[整数部分].[小数部分]
简单起见,整数部分和小数部分都保证非空,且整数部分不会有前导 0。不过,小数部分的最 后可以有 0,因此 0.0 和 0.000 是一样大的。
Input
输入包含不超过 20 组数据。每组数据包含一行,有两个实数(格式如前所述)。每个实数都 包含不超过 100 个字符。
Output
对于每组数据,如果第一个数大,输出"Bigger"。如果第一个数小,输出"Smaller"。如果两个 数相同,输出"Same"。
Sample Input
1.0 2.0
0.00001 0.00000
0.0 0.000
1.0 2.0
0.00001 0.00000
0.0 0.000
Sample Output
Case 1: Smaller
Case 2: Bigger
Case 3: Same
Case 1: Smaller
Case 2: Bigger
Case 3: Same
Source
湖南省第十一届大学生计算机程序设计竞赛
解题思路:
这道题由于输入的数字都没有前导0,并且一定输入按照[整数部分].[小数部分]的格式输入,所有很多情况都不用考虑了,直接找到小数点的位置,比完整数比小数,一位一位比下去,找到不同的就有大小关系,没有就相等。
代码:
#include <iostream>
#include <cmath>
#include <cstdio>
#include <cstring>
using namespace std;
char a[105],b[105];
int main()
{
int ca=0;
while(scanf("%s%s",a,b)!=EOF)
{
ca++;
int i,j;
int len1=strlen(a);
int len2=strlen(b);
for(i=0; i<len1; i++)
{
if(a[i]=='.')
break;
}
for(j=0; j<len2; j++)
{
if(b[j]=='.')
break;
}
if(i<j)
{
printf("Case %d: Smaller\n",ca);
}
else if(i>j)
{
printf("Case %d: Bigger\n",ca);
}
else
{
int flag=0;
for(i=0,j=0; i<len1||j<len2; i++,j++)
{
if(i>=len1)
a[i]='0';
if(j>=len2)
b[i]='0';
if(a[i]<b[i])
{
flag=1;
printf("Case %d: Smaller\n",ca);
break;
}
else if(a[i]>b[i])
{
flag=1;
printf("Case %d: Bigger\n",ca);
break;
}
}
if(flag==0)
printf("Case %d: Same\n",ca);
}
}
return 0;
}
本文介绍了一个简单的算法,用于比较两个实数的大小。通过逐位比较整数部分和小数部分来确定它们之间的大小关系。文章包括问题描述、输入输出格式、示例以及一种有效的解题思路。

365

被折叠的 条评论
为什么被折叠?



