第一次使用 C,我被要求为我的 Systems 类做一个没有 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;
}