📜  TCS编码实践问题|检查奇数或偶数

📅  最后修改于: 2021-05-24 16:34:29             🧑  作者: Mango

给定一个数字,任务是使用命令行参数检查该数字是奇数还是偶数。即使该数字可以被2整除,也会调用该数字;如果该数字不能被2整除,则称为奇数。

例子:

Input: 123
Output: No

Input: 588
Output: Yes

方法:

  • 由于该数字是作为命令行参数输入的,因此不需要专用的输入行
  • 从命令行参数中提取输入数字
  • 提取的数字将为String类型。
  • 将此数字转换为整数类型并将其存储在变量中,例如num
  • 检查此数字是否完全除以2
  • 如果完全可整,则数字为偶数
  • 如果不能完全整除,则该数字为奇数

程序:

C
// C program to check
// if a number is even or odd
// using command line arguments
  
#include 
#include  /* atoi */
  
// Function to the check Even or Odd
int isEvenOrOdd(int num)
{
    return (num % 2);
}
  
// Driver code
int main(int argc, char* argv[])
{
  
    int num, res = 0;
  
    // Check if the length of args array is 1
    if (argc == 1)
        printf("No command line arguments found.\n");
  
    else {
  
        // Get the command line argument and
        // Convert it from string type to integer type
        // using function "atoi( argument)"
        num = atoi(argv[1]);
  
        // Check if it is even or odd
        res = isEvenOrOdd(num);
  
        // Check if res is 0 or 1
        if (res == 0)
            // Print Even
            printf("Even\n");
        else
            // Print Odd
            printf("Odd\n");
    }
    return 0;
}


Java
// Java program to check
// if a number is even or odd
// using command line arguments
  
class GFG {
  
    // Function to the check Even or Odd
    public static int isEvenOrOdd(int num)
    {
        return (num % 2);
    }
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Check if length of args array is
        // greater than 0
        if (args.length > 0) {
  
            // Get the command line argument and
            // Convert it from string type to integer type
            int num = Integer.parseInt(args[0]);
  
            // Get the command line argument
            // and check if it is even or odd
            int res = isEvenOrOdd(num);
  
            // Check if res is 0 or 1
            if (res == 0)
                // Print Even
                System.out.println("Even\n");
            else
                // Print Odd
                System.out.println("Odd\n");
        }
        else
            System.out.println("No command line "
                               + "arguments found.");
    }
}


输出:

  • 在C中:

  • 在Java:
想要从精选的最佳视频中学习并解决问题,请查看有关从基础到高级C++的C++基础课程以及有关语言和STL的C++ STL课程。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程”