【问题标题】:Need help restructuring loop/getting simple average code to work.需要帮助重组循环/让简单的平均代码工作。
【发布时间】: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;

}

【问题讨论】:

  • 不允许定义自己的函数吗?
  • 抱歉,该代码远低于平均水平。去?如果您需要更多帮助,请正确缩进您的提交内容。

标签: c loops average


【解决方案1】:
  1. while(...);中的分号导致无限循环,相当于说:while(...) continue;
  2. 您应该只使用一个循环,并且您应该尝试只使用一个对getchar() 的调用......这与多个getchar() 调用太混淆了,并且您的代码试图按照其编写方式丢弃第一行.
  3. 一定要去掉goto 声明,你的导师不会喜欢它们,而且它们是完全没有必要的。 (请阅读breakcontinue。)
  4. 在直接调用getchar() 的C 解析器中,能够将字符推回输入流非常有用。请参阅 man 3 ungetc 或仅在 getchar(). 周围编写一个简单的包装器,您应该只需要在解析器循环结束时使用一个 pushback 字符。

【讨论】:

  • 欣赏 ;过了一会儿。这绝对不是故意的,我在查看东西时没有发现它。我明白你在说什么,因为我的代码试图丢弃第一行。在我再次编译代码并输入后,它返回的平均值为 0.00。
猜你喜欢
  • 1970-01-01
  • 2011-08-13
  • 2017-09-22
  • 2015-02-11
  • 2011-02-25
  • 2012-03-16
  • 1970-01-01
  • 2012-06-20
  • 1970-01-01
相关资源
最近更新 更多