【问题标题】:How do I write a code that lets a user input different values into arrays如何编写代码让用户将不同的值输入到数组中
【发布时间】:2016-11-11 03:49:51
【问题描述】:

我是 C 的初学者(学习免费资源),我正在尝试编写一个简单的代码来将用户输入的一组数字添加到一组数组中......我做错了什么?

int numbers;
    int number=1;
    int counter = 0;
    int pot[100];
    int calculate;
    int result;

printf("how many numbers do you want to calculate?:"); //asking user how many different integers would be calculated

scanf("%d",&numbers);

while (counter < numbers)

{
    printf("input number %d\n", number);//asking user to input figures to be calculated
    scanf("%d",&pot[0]+1); //user would input values into spaces in the array

    counter++;
    number++;

}


printf("Please press 1 for addition and 2 for multiplication");
scanf("%d",&calculate);

switch (calculate)

{
case 1: result = pot[0]+ pot[0]+1;//this is supposed to add all the individual values within the arrays

printf("the result is %d", result);
break;

case  2: result = pot[0]* pot[0]+1;//this is supposed to multiply all the individual values within the arrays
break;
}



    return 0;

【问题讨论】:

  • 输入、预期输出和实际输出是多少?
  • 什么是&amp;pot[0]+1
  • 抱歉,我不明白这个问题(新手问题)!
  • pot[0]+1 是我试图告诉 C 将用户输入的值分配给数组中的下一个可用空间...假设第一个空间是 pot[0],因此下一个是 pot[1] 等。
  • (1) 检查numbers 是否为&lt;100。 (2) 检查scanf 的返回:while(counter &lt; numbers) { if(scanf("%d", &amp;(pot[counter])) != 1) return 1; counter++; },刚刚开始。请注意,变量counter 是您数组的订阅索引。

标签: c arrays scanf


【解决方案1】:
int numbers;
int number=1;
// int counter = 0; instead used `i`
int pot[100];
int calculate;
int result;
int i = 0;

printf("how many numbers do you want to calculate?:"); //asking user how many different integers would be calculated

scanf("%d",&numbers);

printf("input %d numbers \n", numbers);//asking user to input figures to be calculated

for(i = 0; i < numbers; i++)
{
    printf("input number %d \n", number);
    scanf("%d", &pot[i]);   //user would input values into spaces in the array
    number++;
}

//scanf("%d",&pot[0]+1);     /* this line is wrong*/
//counter++; 
//number++;     


printf("Please press 1 for addition and 2 for multiplication");
scanf("%d",&calculate);

switch (calculate)

{
case 1: result = 0;//this is supposed to add all the individual values within the arrays
        for(i = 0;i < numbers; i++)
        {
             result = result + pot[i];
        }

        printf("the result is %d", result);
        break;

case  2: result = 1;//this is supposed to multiply all the individual values within the arrays
         for(i = 0;i < numbers; i++)
         {
             result = result * pot[i];
         }
         printf("the result is %d", result);
         break;
}



return 0;

此代码应该适用于您的程序。

【讨论】:

  • 不要在循环中增加numbers
  • @Jean-BaptisteYunès numbers 和 number 都是不同的变量。而且我认为初始化结果不会有任何好处,因为一个操作是加法,另一个是乘法。所以,我们必须相应地改变结果的值。
  • 那么消息是错误的:“输入 1 个数字”、“输入 2 个数字”、“输入 3 个数字”等。切勿将两个变量用于同一事物(inumber 是双倍)。 printf("input number %d: ",i+1); 会成功的。
  • 当我运行程序时,我得到这个错误:下标值不是数组、指针或向量
【解决方案2】:

我不确定你到底想做什么,所以这是我的猜测:

int sum(const int *arr, size_t n)
{
    int ret;

    for (ret = 0; --n >= 0; ret += arr[n])
        ;

    return ret;
}
long mpy(const int *arr, size_t n)
{
    long ret;

    for (ret = 1; --n >= 0; ret *= arr[n])
        ;

    return ret;

}
// remove trailing newline
void remTrailingNl(char *buf)
{
    if (buf[strlen(buf) - 1] == '\n')
        buf[strlen(buf) - 1] = '\0';
}

int main()
{
    int *arr, choice, tmp;
    char line[80], *endp;
    size_t n;

    printf("How many numbers are in the array?");
    fgets(line, 80, stdin);
    remTrailingNl(line);
    n = strtol(line, &endp, 10);
    // **endp will be the null character if conversion was successful
    if (**endp == '\0')
        if ((arr = malloc(n * sizeof(int))) == NULL) {
            perror("malloc");
            return 1;
        }

    printf("Begin entering your numbers, each number to a line\n");

    // walking backwards, populate the array
    while (n-- >= 0) {
        fgets(line, 80, stdin);
        remTrailingNl(line);
        tmp = strtol(line, &endp, 10);
        if (**endp == '\0')
            arr[n] = tmp;
        else {
            fprintf(stderr, "Invalid number at position %d\n", n + 1);
            return 1;
        }
    }

    printf("Enter 1 for addition, and 2 for multiplication\n");
    fgets(line, 80, stdin);
    remTrailingNl(line);
    choice = strtol(line, &endp, 10);
    if (**endp == '\0' && choice == 1 || choice == 2) {
        switch (choice) {
            case 1: // add
                printf("Sum is %d\n", sum(arr, n));
                break;
            case 2:
                printf("Product is %ld\n", mpy(arr, n));
                break;
        }
    } else {
        fprintf(stderr, "Invalid choice\n");
        return 1;
    }
    // heap memory must be freed
    free(arr);
    // return 0 on success
    return 0;
}

我们使用long 表示mpy,因为乘法可以给出非常大的答案。另外,不要使用scanf,因为虽然看起来很无辜,但要正确却很棘手。 strtol 更好,因为它可以详细说明号码无效的原因。阅读手册页here。我们在调用fgets 之后立即调用remTrailingNl,因为fgets 总是在缓冲区中放置一个尾随换行符。

【讨论】:

    【解决方案3】:

    如果你想要一个简单的代码来添加数组中的数字,其中数字是由用户给出的,你可以跟着这个。

    int i, num, ans=0, pot[100];
    printf("Give the number of elements:");
    scanf("%d",&num);
    printf("Enter numbers");
    for(i=0;i<num;i++) {
      scanf("%d",&pot[i]);
      ans = ans + pot[i];
    }
    printf("Sum is %d", ans);
    }
    

    这种方式直接显示添加,而不是一次又一次地扫描它,必须循环并再次添加它,一个一个。

    (而且我也是C学习者,如有错误请指正。) 希望这可以简化它。

    【讨论】:

      【解决方案4】:
      So, finally got a working program!!
      
      int pot[100];
      int numbers;
      int count;
      int number = 1;
      int calculate;
      int result;
      
      
      printf("how many numbers do you want to calculate:");
      scanf("%d", &numbers);
      
      for(count=0;count<numbers;count++)
      
      {
      printf("enter number %d:\n", number);
      scanf("%d",&pot[count]);
      number++;
      
      }
      
      printf("Please press 1 for addition and 2 for multiplication");
      scanf("%d",&calculate);
      
      switch (calculate)
      
      {
      case 1: result = 0;
      
              for(count = 0;count < numbers; count++)
              {
                   result = result + pot[count];
              }
      
              printf("the result is %d", result);
              break;
      
      case  2: result = 1;
      
               for(count = 0;count< numbers; count++)
               {
                   result = result * pot[count];
               }
               printf("the result is %d", result);
               break;
      }
      

      返回 0;

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-08-14
        • 2014-04-11
        • 2014-11-07
        • 1970-01-01
        • 2017-09-12
        相关资源
        最近更新 更多