【问题标题】:Why is "1" being stored in all array index positions?为什么“1”存储在所有数组索引位置?
【发布时间】:2015-11-08 19:57:38
【问题描述】:

我正在学习和练习 C。除了输出格式。我不明白为什么所有数组元素都输出“1”,或者数字甚至来自哪里。

即使我输入了5个“5”,输出仍然是“1”。

#define LIMIT 5
#include <stdio.h>
#include<stdlib.h>
void getNums();

int main() {
    getNums();
    return 0;
}

void getNums() {
    int newRay[LIMIT];
    for(int i = 0; i < 5; i++) {
        int element;
        int result = scanf("%d", &element); 
        newRay[i] = result;
        printf("%d", newRay[i]);
    }
}

【问题讨论】:

    标签: c arrays for-loop printf


    【解决方案1】:

    result 存储scanf 的返回值,即提供给scanf 的格式字符串中的匹配数。你真正想要的是读取的值,存储在element

            newRay[i] = element;
    

    注意事项:

    • 更好地始终使用LIMIT。您的程序可能只是“quick'n'dirty”,但无论如何您都应该替换for-loop 中的5

    【讨论】:

      【解决方案2】:

      scanf 返回成功分配输入的数量。在您的情况下,如果对 element 的分配成功,则返回 1。

      您可能打算使用:

          newRay[i] = element;
      

      你应该做的是:

          int result = scanf("%d", &element);
          if ( result == 1 )
          {
             newRay[i] = element;
          }
          else
          {
             // Unable to read the input
             // Deal with error.
          }
      

      【讨论】:

        【解决方案3】:

        您将scanf 的返回值分配给数组元素。 scanf 返回分配的输入项数。

        scanf("%d", &amp;element);中,只分配了一个输入项,所以它会返回1

        改变

        int result = scanf("%d", &element); 
        newRay[i] = result;  
        

        scanf("%d", &element);
        newRay[i] =  element
        

        【讨论】:

          【解决方案4】:

          你得到“1”作为结果的原因是你只捕获了 scanf 函数的返回值。您输入的值由 scanf 返回,但它被复制到元素(您通过引用它来使用 - &element)。不需要结果变量。

          void getNums(){ int newRay[LIMIT]; int element; for(int i=0; i<5;i++){ scanf("%d",&element); newRay[i] = element; printf("%d", newRay[i]); } }

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2021-01-17
            • 2021-11-25
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多