如何将用户希望的适当输入附加为整数到一个数组中,在C语言中?

huangapple go评论50阅读模式
英文:

How do i append proper input as integers to an array in C, as long the user wishes to?

问题

    int main(){
        
        char answer; 
        int numbers[100];
        int i = 0;
        int size;
        int max = -9999;
    
        do{
    
            printf("请输入一个数字:");
            scanf("%d", &numbers[i]);
            printf("是否继续添加数字:(Y/N)");
            scanf(" %c", &answer);  // 注意加一个空格,避免之前输入的换行符被读取
            i++;
    
        }while(answer == 'Y');
    
    
        size = sizeof(numbers)/sizeof(numbers[0]);
        for(int j = 0; j<size; j++){
            if(numbers[j]>= max){
                max = numbers[j];
            }
        }
    
        printf("最大的数字是:%d", max);
    
    
    return 0;
    
    }
英文:
int main(){
    
    char answer; 
    int numbers[100];
    int i = 0;
    int size;
    int max = -9999;

    do{

        printf(&quot;Please enter an number: &quot;);
        scanf(&quot;%d&quot;, &amp;numbers[i]);
        printf(&quot;Would you like to keep adding numbers:(Y/N)&quot;);
        scanf(&quot;%c&quot;, &amp;answer);
        scanf(&quot;%c&quot;);
        i++;

    }while(answer == &#39;Y&#39;);


    size = sizeof(numbers)/sizeof(numbers[0]);
    for(int j = 0; j&lt;size; j++){
        if(numbers[j]&gt;= max){
            max = numbers[j];
        }
    }

    printf(&quot;The max number is: %d&quot;, max);


return 0;

}

Hello beginner in C, here in my code i am trying to take an arbitrary amount of (the user enters Y if he/she wishes to enter another number.) input as integers and add them to an array and find the maximum of the input using a for loop, however i am not getting the correct output. What could be the error in my code?

答案1

得分: 2

问题包括:

在预期为字母时读取 &#39;\n&#39;

scanf(&quot;%c&quot;, &amp;answer); 在先前输入数字(例如:<kbd>9</kbd>)之后读取字符,这很可能是先前输入的 `'\n'' <kbd>Enter</kbd>。

使用空格来消耗前导空白字符,如 &#39;\n&#39;',空格,制表符...

// scanf(&quot;%c&quot;, &amp;answer);
scanf(&quot; %c&quot;, &amp;answer);

启用所有警告

无效/不必要的代码 scanf(&quot;%c&quot;); 将在启用了良好编译器的情况下引发编译器警告。

  • 这个答案中的最佳建议:启用所有编译器警告以节省时间。

INT_MIN 开始

最大输入可能小于 -9999。
&lt;limits.h&gt; 中的 INT_MIN

// int max = -9999;
int max = INT_MIN;

迭代到 i

与其迭代到100,只需要迭代到 i,输入的值的计数。

// for(int j = 0; j&lt;size; j++){
for(int j = 0; j&lt;i; j++){

检查返回值

scanf() 返回一个值,表示成功转换的数量。使用它来验证成功发生了输入。

// scanf(&quot;%d&quot;, &amp;numbers[i]);
if (scanf(&quot;%d&quot;, &amp;numbers[i]) != 1) {
  ; // 使用待定代码报告错误。
}

不要循环太多次

// } while(answer == &#39;Y&#39;);
} while(answer == &#39;Y&#39; &amp;&amp; i &lt; 100); 

没有保存值数组的必要

最大值可以在输入数据时计算。

int max = INT_MIN;
do {
  int num;
  printf(&quot;请输入一个数字:&quot;);
  if (scanf(&quot;%d&quot;, number) != 1) {
    break;
  }
  if (num &gt; max) {
    max = num;
  }
  printf(&quot;是否继续添加数字:(Y/N)&quot;);
  if (scanf(&quot; %c&quot;, &amp;answer) != 1) {
    break;
  }
} while (answer == &#39;Y&#39; || answer == &#39;y&#39;);
printf(&quot;最大数字是:%d&quot;, max);

----

**未来的改进**

* 处理超出 `int` 范围的值。研究 `intmax_t`。

* 检测没有输入有效数据的情况。研究 `fgets()`。

* 检测非有效的 `Y/N` 输入。研究 `fgets()`。

* 恢复,而不是因无效输入而退出循环。

<details>
<summary>英文:</summary>

Problems include:

**Reading a `&#39;\n&#39;` when a letter is expected**

`scanf(&quot;%c&quot;, &amp;answer);` reads the character after the prior input of a number (example:&lt;kbd&gt;9&lt;/kbd&gt;), which is likely the prior entry&#39;s `&#39;\n&#39;` &lt;kbd&gt;Enter&lt;/kbd&gt;.

Use a space to consume leading white-space like `&#39;\n&#39;`, space, tab, ...

    // scanf(&quot;%c&quot;, &amp;answer);
    scanf(&quot; %c&quot;, &amp;answer);

**Enable all warnings**

Invalid/unnecessary code `scanf(&quot;%c&quot;);` will raise a compiler warning with a well enabled compiler.

* Best advice in this answer: enable all compiler warnings to save time.

**Start at `INT_MIN`**

The maximum input may be less than -9999.  
`INT_MIN` in `&lt;limits.h&gt;`

    // int max = -9999;
    int max = INT_MIN;


**Iterate to `i`**

Rather than iterate to 100, only need to iterate to `i`, the count of values entered.

    // for(int j = 0; j&lt;size; j++){
    for(int j = 0; j&lt;i; j++){

**Check return values**

`scanf()` returns a value indicated the number of successful conversions.  Use it to validated input successfully happened.

    // scanf(&quot;%d&quot;, &amp;numbers[i]);
    if (scanf(&quot;%d&quot;, &amp;numbers[i]) != 1) {
      ; // Report error with TBD code.
    }

**Do not loop too often**

    // } while(answer == &#39;Y&#39;);
    } while(answer == &#39;Y&#39; &amp;&amp; i &lt; 100); 

**There is no reason to save an array of values**

The maximum could be calculated as data is entered.


    int max = INT_MIN;
    do {
      int num;
      printf(&quot;Please enter an number: &quot;);
      if (scanf(&quot;%d&quot;, number) != 1) {
        break;
      }
      if (num &gt; max) {
        max = num;
      }
      printf(&quot;Would you like to keep adding numbers:(Y/N)&quot;);
      if (scanf(&quot; %c&quot;, &amp;answer) != 1) {
        break;
      }
    } while (answer == &#39;Y&#39; || answer == &#39;y&#39;);
    printf(&quot;The max number is: %d&quot;, max);

----

**Future Improvements**

* Handle values outside `int` range.  Research `intmax_t`.

* Detect case of no valid input entered.  Research `fgets()`

* Detect non-valid `Y/N` input.  Research `fgets()`

* Recover, rather than quit loop with invalid input.


</details>



huangapple
  • 本文由 发表于 2023年2月8日 19:49:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/75385381.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定