📜  TCS 编码练习题 |最大的 3 个数字

📅  最后修改于: 2021-10-23 07:37:49             🧑  作者: Mango

给定三个数字,任务是使用命令行参数找到三个数字中最大的一个。

例子

Input: A = 2, B = 8, C = 1
Output: 8

Input: A = 231, B = 4751, C = 75821
Output: 75821

方法:

  • 由于数字是作为命令行参数输入的,因此不需要专用的输入行
  • 从命令行参数中提取输入数字
  • 提取的数字将是字符串类型。
  • 将这些数字转换为整数类型并将其存储在变量中,例如 A、B 和 C
  • 找出最大的数字如下:
    • 检查 A 是否大于 B。
      • 如果为真,则检查 A 是否大于 C。
        • 如果为真,则打印“A”作为最大数字。
        • 如果为 false,则打印 ‘C’ 作为最大数字。
      • 如果为假,则检查 B 是否大于 C。
        • 如果为真,则打印 ‘B’ 作为最大数字。
        • 如果为 false,则打印 ‘C’ 作为最大数字。
  • 打印或返回最大的数字

程序:

C
// C program to compute the greatest of three numbers
// using command line arguments
  
#include 
#include  /* atoi */
  
// Function to compute the greatest of three numbers
int greatest(int A, int B, int C)
{
  
    if (A >= B && A >= C)
        return A;
  
    if (B >= A && B >= C)
        return B;
  
    return C;
}
  
// Driver code
int main(int argc, char* argv[])
{
  
    int num1, num2, num3;
  
    // 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)"
        num1 = atoi(argv[1]);
        num2 = atoi(argv[2]);
        num3 = atoi(argv[3]);
  
        // Find the greatest and print it
        printf("%d\n", greatest(num1, num2, num3));
    }
    return 0;
}


Java
// Java program to compute the greatest of three numbers
// using command line arguments
  
class GFG {
  
    // Function to compute the greatest of three numbers
    static int greatest(int A, int B, int C)
    {
  
        if (A >= B && A >= C)
            return A;
  
        if (B >= A && B >= C)
            return B;
  
        return C;
    }
  
    // 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 num1 = Integer.parseInt(args[0]);
            int num2 = Integer.parseInt(args[1]);
            int num3 = Integer.parseInt(args[2]);
  
            // Find the greatest
            int res = greatest(num1, num2, num3);
  
            // Print the greatest
            System.out.println(res);
        }
        else
            System.out.println("No command line "
                               + "arguments found.");
    }
}


输出:

  • 在 C 中:

  • 在Java:

想要从精选的视频和练习题中学习,请查看C++ 基础课程,从基础到高级 C++ 和C++ STL 课程,了解语言和 STL。要完成从学习语言到 DS Algo 等的准备工作,请参阅完整的面试准备课程