您的位置:首页 > 其它

UVa465 switch语句——愿天下再无WA

2017-01-13 15:53 363 查看
这些是可以通过测试的,但是删去 ch=='*'&& 不行 ?原因——对比正解!注意break语句位置的变化
//uva 465
#include<stdio.h>
#include<limits.h>
#include<string.h>
#include<stdlib.h>
char num1[10000];
char num2[10000];
bool fits(char* s);
int main()
{
//freopen("input.txt", "r", stdin);
char ch;
while(scanf("%s %c %s", num1, &ch, num2) == 3)
{
printf("%s %c %s\n", num1, ch, num2);
bool cal = true;
if(fits(num1) == false)
{
printf("%s\n","first number too big");
cal = false;
}
if(fits(num2) == false)
{
printf("%s\n","second number too big");
cal = false;
}

if(ch == '*')
{
if((fits(num1)&&atoi(num1)==0)||(fits(num2)&&atoi(num2)==0))
continue;
}

if(cal == false)
printf("result too big\n");
else
{
double n1 = atof(num1);
double n2 = atof(num2);

switch(ch)
{
case '+':
if( n1 + n2> INT_MAX)
{
printf("%s\n","result too big");
continue;
}
case '*':
if(ch=='*' && n1 *n2 > INT_MAX)            //删去 ch=='*'&& 不行
{
printf("%s\n","result too big");
break;
}
}

/* //将switch替换成这个,通过测试
if(ch == '+' && n1 + n2> INT_MAX)
{
printf("%s\n","result too big");

}

if(ch=='*' && n1 *n2 > INT_MAX)
{
printf("%s\n","result too big");

}
*/
}
}
}
bool fits(char* ss)
{
char limit[15];
sprintf(limit,"%d",INT_MAX);
char s[10000];
memset(s, 0, sizeof(s));
int i;
for(i = 0; i < strlen(ss)&&ss[i] == '0'; i++);
if(i == strlen(ss)) i--;
strcpy(s,ss+i);

if(strlen(s) > strlen(limit))
return false;
else if(strlen(s) == strlen(limit))
{
return strcmp(limit, s) >=0;
}
else return true;
}
正解:

//uva 465
#include<stdio.h>
#include<limits.h>
#include<string.h>
#include<stdlib.h>
char num1[10000];
char num2[10000];
bool fits(char* s);
int main()
{
//freopen("input.txt", "r", stdin);
char ch;
while(scanf("%s %c %s", num1, &ch, num2) == 3)
{
printf("%s %c %s\n", num1, ch, num2);
bool cal = true;
if(fits(num1) == false)
{
printf("%s\n","first number too big");
cal = false;
}
if(fits(num2) == false)
{
printf("%s\n","second number too big");
cal = false;
}

if(ch == '*')
{
if((fits(num1)&&atoi(num1)==0)||(fits(num2)&&atoi(num2)==0))
continue;
}

if(cal == false)
printf("result too big\n");
else
{
double n1 = atof(num1);
double n2 = atof(num2);

switch(ch)
{
case '+':
if( n1 + n2> INT_MAX)
printf("%s\n","result too big");
break;
case '*':
if(n1 *n2 > INT_MAX) //删去 ch=='*'&& 不行
printf("%s\n","result too big");
break;
}

/* //将switch替换成这个,通过测试
if(ch == '+' && n1 + n2> INT_MAX)
{
printf("%s\n","result too big");

}

if(ch=='*' && n1 *n2 > INT_MAX)
{
printf("%s\n","result too big");

}
*/
}
}
}
bool fits(char* ss)
{
char limit[15];
sprintf(limit,"%d",INT_MAX);
char s[10000];
memset(s, 0, sizeof(s));
int i;
for(i = 0; i < strlen(ss)&&ss[i] == '0'; i++);
if(i == strlen(ss)) i--;
strcpy(s,ss+i);

if(strlen(s) > strlen(limit))
return false;
else if(strlen(s) == strlen(limit))
{
return strcmp(limit, s) >=0;
}
else return true;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  switch