这个代码在我的电脑上工作得很好,而我用codeblocks 10.05编译它。代码不会给出任何错误或警告!但是在将它提交给在线评判编码社区时,他们会回复我一个编译错误! 这是我的代码:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int j=1;
while(j=1){
int x,y,i,j,num,count=0,p,k;
for(;;){
printf("enter two integers. they must not be equal and must be between 1 and 100000\n");
scanf("%d%d",&i,&j);
if(i>=1 && i<100000 && j>=1 && j<100000 && i!=j){
break;
}
else{
printf("try the whole process again\n");
}
}
if(i>j){
x=i;
y=j;
}
else{
x=j;
y=i;
}//making x always greater than y
int *cyclelength=(int *)malloc(5000*sizeof(int));
if (NULL==cyclelength){
printf("process aborted");
return 0;
}
else{
/*solution part for the range of number. and solution for each number put into cyclelength.*/
num=y;
while(num<=x){
p=1;
k=num;
while(k!=1){
if(k%2==0)
k=k/2;
else
k=3*k+1;
p+=1;
}
cyclelength[count]=p;
num+=1;
count+=1;
}
int c=0;
int max=cyclelength[c];
for(c=0;c<x-y-1;c+=1){
if(max<cyclelength[c+1]){
max=cyclelength[c+1];
}
}
free(cyclelength);
cyclelength = NULL;
printf("%d,%d,%d\n",i,j,max);
}
}
}
当我尝试在 ANSI C 4.1.2 - GNU C编译器下的在线社区中提交它时,选项:-lm -lcrypt -O2 -pipe -ansi -DONLINE_JUDGE 这种格式。他们发给我一个编译错误信息!
Our compiler was not able to properly proccess your submitted code. This is the error returned:
code.c: In function 'main':
code.c:25:10: error: expected expression before '/' token
code.c:27:19: error: 'cyclelength' undeclared (first use in this function)
code.c:27:19: note: each undeclared identifier is reported only once for each function it appears in
code.c:10:18: warning: ignoring return value of 'scanf', declared with attribute warn_unused_result
为什么我会这样?我的错在哪里?编码格式不匹配吗?我是初学者!
答案 0 :(得分:1)
使用-ansi选项,错误是ANSI合规性失败:
}//making x always greater than y
应该是
} /* making x always greater than y */
在第26行;你不能在这里宣布循环长度;它需要位于函数的顶部(第5行)
int main()
{
int *cyclelength;
...
cyclelength=(int *)malloc(5000*sizeof(int));
scanf问题是一个警告,因为不检查scanf的返回值会假定它已成功;所以你应该做点什么:
do {
printf("enter two integers. they must not be equal and must be between 1 and 100000\n");
number_read = scanf("%d%d", &i, &j);
if (number_read < 0) /* read failed, e.g. user entered ctrl-d */
return 0;
} while (number_read != 2);
当然,您需要在函数顶部声明number_read
答案 1 :(得分:0)
您的代码不是ANSI C - 您无法像在C ++和C99中那样在块的中间定义变量。将cyclelength
,c
,max
等的声明移到各自块的顶部。对于严格的ANSI,您还需要使用仅限C的注释,即将// comment
更改为/* comment */
。