简体   繁体   English

为什么这个程序打印 0?

[英]Why this program prints 0?

I am supposed to write a program that prints the minimum value from vector.This is what i tried.我应该编写一个程序来打印 vector 的最小值。这就是我尝试过的。 It only prints 0. I tried to change the sign both ways but it doesnt work.它只打印 0。我尝试用两种方式更改符号,但它不起作用。

#include <stdio.h>

int read(int v[], int size)
{
    int i = 0;
    do
    {
        scanf("%i", &v[i]);
        i++;
    } while (v[i-1] != 0 && i < size);
    int n = i;
    return n;
}
   
int minim(int v[], int n)
{
    int m;
    m = v[0];
    int i;
    for (i = 1; i <= n-1; i++)
    {
        if (v[i] < m)
        {
            m = v[i];           
        }     
    }
    return m;  
}

int main()
{
    int arr[100];
    int n = read(arr, 100);
      
    int min = minim(arr, n);
    printf("\nMinimum vrom vector is %i\n", min);
    return 0;
}   

Since your scanf loop (I'd recommend staying away from function names like read , which are part of the C standard, even if you didn't include unistd.h ) ends when 0 is entered, you need to include a check at the end to decrement the size of the array if 0 is the last entry.由于您的scanf循环(我建议远离 function 名称,如read ,它们是 C 标准的一部分,即使您没有包含unistd.h )在输入 0 时结束,您需要在如果 0 是最后一个条目,则 end 减少数组的大小。 Basically, replace everything after your do-while loop with this:基本上,将 do-while 循环之后的所有内容替换为:

if (v[i - 1]) {
    return i;
}
return --i;

This will return i if all 100 elements are non-zero, otherwise it will decrement to remove the 0 from your array before returning.如果所有 100 个元素都非零,这将返回i ,否则它将递减以在返回之前从数组中删除 0。 No need to declare int n=i just to instantly return n .无需声明int n=i即可立即return n

Edit: I saw your comment that it worked properly for finding the maximum.编辑:我看到你的评论说它可以正常找到最大值。 This is because you almost certainly entered a number into the array that's greater than 0, so adding 0 at the end would not affect the maximum number.这是因为您几乎肯定在数组中输入了一个大于 0 的数字,因此在末尾添加 0 不会影响最大数字。 Try finding the max again, but only enter negative numbers.尝试再次找到最大值,但只输入负数。 The result will be 0.结果将为 0。

read() uses a 0 entry to terminate reading more input. read()使用0条目来终止读取更多输入。 Yet that 0 is included in the array and counts toward the array length as part of the return value.然而,0 包含在数组中,并作为返回值的一部分计入数组长度。

Instead, only increment the array count when input was numeric and non-zero.相反,仅当输入为数字且非零时才增加数组计数。

int read(int v[], int size) {
    int i = 0;
    while (i < size) {
        // Also test if valid numeric input was read.
        if (scanf("%i", &v[i]) != 1) {
            break;
        }
        // Stop if a 0 was read
        if (v[i] == 0) {
            break;
        }
        // Now increment
        i++;
    }
   
    return i;
}

Could use shorter code, yet it is less readable.可以使用更短的代码,但可读性较差。 Best to code for clarity.最好编码清楚。

int read(int v[], int size) {
    int i = 0;
    while (i < size && scanf("%i", &v[i]) == 1 && v[i]) {
        i++;
    }
    return i;
}

The test condition测试条件

while (v[i-1] != 0

checks whether the last element read was 0 , after it was successfully processed and converted by scanf (but you never checked the return value).检查最后读取的元素是否为0 ,在它被scanf成功处理和转换后(但你从未检查过返回值)。 The 0 is then included in the array, and will always be the minimum unless you enter a non-negative number.然后0包含在数组中,除非您输入非负数,否则它将始终是最小值。

Here's the working code:这是工作代码:

#include <stdio.h>
#include <stdlib.h> 
    
static size_t read (int v[], size_t size)
{
      size_t i = 0;
      do
      {
          /* Check if scanf was successful */ 
          if (scanf("%i",&v[i]) != 1) 
          {
              fprintf(stderr, "Error: Invalid input.\n"); 
              return EXIT_FAILURE;
          }
          i++;
          } while (v[i - 1] != 0 && i < size);

      /* Also check whether the last element read was 0 */ 
      if (v[i - 1] == 0) {
          i--;
      } 
      return i;
 }
       
static int minim (int v[],size_t n)
{
     int min;
     min = v[0];
           
     for(size_t i = 1; i < n; i++) {
            if (v[i] < min) {
                min = v[i]; 
            }        
     }
     return min;  
}

int main(void)
{
     int arr[100];
     size_t n = read(arr,100);
                
     int min = minim(arr,n);
     printf("\nMinimum vrom vector is %i\n", min);
     return EXIT_SUCCESS;
 }

I made some minor changes to it.我对它做了一些小改动。 Though I'm not satisfied with the design.虽然我对设计不满意。

Sample I/O:示例 I/O:

20
8
18
60
39
56
0
Minimum vrom vector is 8

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM