【问题标题】:C Reading negative and positive numbers from file into ArrayC将文件中的负数和正数读入数组
【发布时间】:2016-05-03 14:47:49
【问题描述】:

我想从文件中读取数字,每个数字都在一个新行上,它们是十进制数,其中一些是负数。我想将它们存储到一个数组中并计算文件中有多少个数字。 我知道下面的代码计算数字,但它只计算文件中的正数。我尝试将 '0' 更改为负值,但它们不起作用,它不会给出错误,但它总是不会给出正确的输出。如何计算负数和正数?

 int main()
    {
            double a[MAX];
            double num;
            int n = 0;

            scanf("%lf", &num);
            while (num >=0) {
                a[n] = num;
                n++;
                scanf("%lf", &num);
            }
    }

【问题讨论】:

  • while (n < MAX && scanf("%lf", &num) == 1) { a[n++] = num; }

标签: c arrays file


【解决方案1】:

你的逻辑有问题。一旦找到第一个非正数,您将立即中断循环。此外,您并不确定您没有使用 a 越界。你需要使用:

while ( n < MAX && scanf("%lf", &num) == 1 )
{
   if ( num >= 0 )
   {
      a[n] = num;
      n++;
   }
}

如果要计算所有非零数字,请使用:

while ( n < MAX && scanf("%lf", &num) == 1 )
{
   if ( num != 0 )
   {
      a[n] = num;
      n++;
   }
}

由于您将在while 循环的条件中读取数字,因此请删除循环前的scanf 行。

【讨论】:

  • @EbonyDoe,既然你接受了我的回答,我假设你不需要更多的澄清。如果没有,请告诉我。
【解决方案2】:
while (num >=0)

一旦您读取到负数,此循环条件就会中断。一旦文件中没有更多数字要读取,您就可以结束循环,并计算过程中的正数:

int main()
{
        double a[MAX];
        double num;
        int n = 0;

        while (n < MAX && scanf("%lf", &num) == 1) {
            a[n] = num;
            n++;
        }

        // to count positives, zeros, negatives
        int np, nz, ng;
        np = nz = ng = 0;
        for (int i = 0; i < n; i++) {
            if (a[i] > 0) np++;
            else if (a[i] == 0) nz++;
            else ng++;
        }
        printf("%d %d %d\n", np, nz, ng);
}

【讨论】:

    猜你喜欢
    • 2021-01-03
    • 1970-01-01
    • 1970-01-01
    • 2020-01-20
    • 2010-09-29
    • 1970-01-01
    • 2016-12-10
    • 1970-01-01
    相关资源
    最近更新 更多