类型的差别造成奇怪的运行结果——输出错误、无法继续输入等
新增:
找出下面代码的错误:
# include <stdio.h>
# include <string.h>
# define MAXN 10005
int main()
{
short m, n, i, ans, tmp, t[MAXN];
while (~scanf("%d%d", &n, &m))
{
memset(t, 0, sizeof(t));
for (i = 1; i <= m; ++i)
{
scanf("%d", &tmp);
t[tmp] = t[tmp]+1;
}
ans = tmp = 0;
for (i = 1; i <= n; ++i)
if (t[i] > tmp)
{
tmp = t[i];
ans = i;
}
printf("%d\n", ans);
}
return 0;
}
题一:输入两个实数(0~1000),输出它们的和,并保留四位小数(多组输入)。
wrong
# include <stdio.h>
int main()
{
double a,b;
while (scanf("%f%f", &a,&b))
printf("%.4f\n", a+b);
return 0;
}
right
# include <stdio.h>
int main()
{
double a,b;
while (scanf("%lf%lf", &a,&b))
printf("%.4lf\n", a+b);
return 0;
}
题二:输入两个整数(0~1000),输出它们的和(多组输入)。
wrong
# include <stdio.h>
int main()
{
short int a,b;
while (scanf("%d%d", &a,&b))
printf("%d\n", a+b);
return 0;
}
right
# include <stdio.h>
int main()
{
int a,b;
while (scanf("%d%d", &a,&b))
printf("%d\n", a+b);
return 0;
}
找出下列代码错误之处:
wrong
// 1003 UC Browser
# include <stdio.h>
# define MAXN 105
short int expr[] = {0,1,3,6,10,15};
int main()
{
short int T, n, tot, cnt, i;
char a[MAXN];
scanf("%d", &T);
while (T > 0)
{
scanf("%d%s", &n,a);
tot = 0;
for (i=0; i<n; ++i)
{
cnt = 0;
while ('1'==a[i]){++cnt;++i;}
tot += (cnt/5)*15+expr[cnt%5];
}
printf("%d\n",(tot<75 ? (tot+5)/10:8));
--T;
}
return 0;
}
正确的在这里:
right
// 1003 UC Browser
# include <stdio.h>
# define MAXN 105
short int expr[] = {0,1,3,6,10,15};
int main()
{
int T, n, tot, cnt, i; // short int 改为 int
char a[MAXN];
scanf("%d", &T);
while (T > 0)
{
scanf("%d%s", &n,a);
tot = 0;
for (i=0; i<n; ++i)
{
cnt = 0;
while ('1'==a[i]){++cnt;++i;}
tot += (cnt/5)*15+expr[cnt%5];
}
printf("%d\n",(tot<75 ? (tot+5)/10:8));
--T;
}
return 0;
}