【问题标题】:Use multiple variables in a loop在循环中使用多个变量
【发布时间】:2021-02-22 07:37:23
【问题描述】:

我正在尝试检查五个数字是奇数还是偶数。我想使用一个迭代 5 次的 for 循环,并使用一个 for 循环来检查数字是奇数还是偶数。

代码:

#include <stdio.h>

int main()
{
    int a ,b ,c ,d ,e;

    scanf("%d %d %d %d %d", &a, &b ,&c ,&d ,&e);

    int count = 5;

    for (int i = 0; i < count; i++)
    {
        
        if(num % 2 == 0) //num should be a then b then c etc.

        printf("even");

        else

        printf("odd");
    }

}   

我找不到任何有关在循环/语句中交换/切换变量的信息。如果有人有答案或在哪里可以找到信息,我将永远感激不尽!

提前致谢! //新手程序员

【问题讨论】:

  • 您不需要单独的变量,甚至不需要数组,只需要一个保存当前输入的变量。然后将输入的读取放入循环本身
  • 似乎我在谷歌上搜索了错误的问题,当使用数组时,我得到了数百万个示例/答案!谢谢!
  • 如果你是 C 和编程的绝对初学者,那么我真的建议你投资一些初学者书籍(或者甚至可能参加一些课程)来学习。虽然在 Internet 上很容易找到教程和示例,但好的并不多,有些甚至可能包含错误或错误的信息。一旦你掌握了基础知识,就会更容易发现不好或错误的示例或教程。

标签: c for-loop if-statement variables


【解决方案1】:

也许您可以scanf into an array of integers,而不是扫描到不同的变量(a、b 等)。

然后你可以使用数组的索引。

int num = numbers[i];

在 for 循环中。

【讨论】:

    【解决方案2】:

    正如我在评论中提到的,这可以只用一个变量而不用数组来解决:

    #include <stdio.h>
    
    int main()
    {
        unsigned const count = 5;
    
        for (unsigned i = 0; i < count; i++)
        {
            printf("Please enter a number: ");
            fflush(stdout);  // To make sure the output is printed
    
            int number;
            scanf("%d", &number); // Note: Doesn't handle errors
    
            if (number % 2 == 0)
            {
                printf("The number %d is even\n", number);
            }
            else
            {
                printf("The number %d is odd\n", number);
            }
        }
    }
    

    【讨论】:

      【解决方案3】:

      如果你不想学习数组,有一种硬核方法:

      for (int i = 0; i < count; i++)
      {
          switch(i)
          {
              case 0: 
                  num = a;
                  break;
              case 1: 
                  num = b;
                  break;
      
              /* etc etc etc */
          }
      }
      

      【讨论】:

      • 现在试试 10 个数字,或者 20 个等 ;)
      • 正如我所写的那样,这是一种硬核方式:)
      猜你喜欢
      • 2022-11-15
      • 2021-10-22
      • 1970-01-01
      • 1970-01-01
      • 2014-06-02
      • 2019-01-26
      • 2015-01-02
      • 1970-01-01
      相关资源
      最近更新 更多