C 需要帮助重组循环/使简单的平均代码正常工作。
第一次使用C时,我被要求为我的系统类做一个没有scanf(仅使用getchar)的简单平均函数。我最终编写了一个不必要的复杂循环,只是为了让代码进行编译,即使在编译+运行之后,它在接受键盘输入后似乎也没有任何作用C 需要帮助重组循环/使简单的平均代码正常工作。,c,loops,average,C,Loops,Average,第一次使用C时,我被要求为我的系统类做一个没有scanf(仅使用getchar)的简单平均函数。我最终编写了一个不必要的复杂循环,只是为了让代码进行编译,即使在编译+运行之后,它在接受键盘输入后似乎也没有任何作用 #include <stdio.h> #include <stdlib.h> //average program //use getchar to get numbers separately instead of scanf and integers. /
#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;
}
#包括
#包括
//平均程序
//使用getchar分别获取数字,而不是scanf和整数。
//不知道为什么。最有可能塑造性格。
int main(int argc,const char*argv[]
{
字符x,z;
浮动平均值;
总积分,n,b;
printf(“输入1到100之间的整数值。用空格分隔每个值。例如:23 100 99 1 76\n”);
ret:
x=getchar();
而(x!='\n');
{
如果(x==isspace(x))
{goto ret;}
门诊部:
z=getchar();
如果((z==isspace(z)))
{
b=x-“0”;//从任何字符数字中减去0将返回整数值
tot+=b;
n++;
后藤网;
}
else如果(z='\n')
{
b=x-‘0’;
tot+=b;
n++;
转到终点;
}
其他的
{
x=x*10;
x=x+z;
转到门诊部;
}
}
完:
平均值=tot/n;
printf(“取平均值。平均值为%1.2f\n”,平均值);
返回平均值;
}
while(…)中的分号代码>导致无限循环,这与说:同时(…)继续相同代码>
getchar()
的调用。。。它太容易与多个getchar()
调用混淆,并且您的代码试图以编写方式丢弃第一行getchar()
的C解析器中,能够将字符推回到输入流上非常有用。请参见man3 ungetc
或仅围绕getchar()编写一个简单的包装。
在解析器循环的末尾,您应该只需要一个字符的pushback您不允许定义自己的函数吗?抱歉,但代码远远低于平均值。后藤?如果您需要更多帮助,请适当缩进您提交的内容;过了一段时间。这肯定不是故意的,我在看东西的时候也没有抓到。通过我的代码试图扔掉第一行,我明白了你的意思。在我再次编译代码并给它输入后,它返回的平均值为0.00。