【发布时间】:2013-01-27 03:39:55
【问题描述】:
第一次使用 C,我被要求为我的系统类做一个简单的平均函数,而不使用 scanf(仅使用 getchar)。我最终编写了一个不必要的复杂循环,只是为了让我的代码能够编译,即使在编译+运行之后,在接受键盘输入后它似乎也没有做任何事情。
#include <stdio.h>
#include <stdlib.h>
//average program
//use getchar to get numbers separately instead of scanf and integers.
//Not sure why. Most likely to build character.
int main (int argc, const char * argv[])
{
char x,z;
float avg;
int tot,n,b;
printf("Input Integer values from 1 to 100. Separate each value by a space. For example: 23 100 99 1 76\n");
ret:
x=getchar();
while( x != '\n' );
{
if(x==isspace(x))
{ goto ret;}
opd:
z=getchar();
if ((z == isspace(z)))
{
b = x - '0';//subtracting 0 from any char digit returns integer value
tot +=b;
n++;
goto ret;
}
else if(z == '\n')
{
b = x - '0';
tot +=b;
n++;
goto end;
}
else
{
x = x*10;
x = x + z;
goto opd;
}
}
end:
avg=tot/n;
printf("Taking of the average of the values. The average is %1.2f\n",avg);
return avg;
}
【问题讨论】:
-
不允许定义自己的函数吗?
-
抱歉,该代码远低于平均水平。去?如果您需要更多帮助,请正确缩进您的提交内容。