C 程序使用 switch case 查找两个数字之间的最大值

问题描述 投票:0回答:3
/* C program to find maximum between two numbers using switch case */

#include <stdio.h>

void main() {
    int m, n;
    printf("\nEnter the first number\n");
    scanf("\n%d", &m);
    printf("\nEnter the second number\n");
    scanf("\n%d", &n);

    switch (m > n) { /* it will give result either as 0 or 1*/
      case 0:
        printf("\nThe greater number is %d\n", n);
        break;
      case 1:
        printf("\nThe greater number is %d\n", m);
        break;
      default:
        printf("\nBoth number's are same\n");
    }
}

我收到一条错误,指出

switch
条件具有布尔值。

请帮助我,我哪里出错了?

c
3个回答
2
投票

m > n
switch
的有点不寻常的控制表达式。允许的值为
1
(当
m > n
时)或
0
(当
m <= n
时)。发出警告是因为您定义了多余的
default
标签,该标签被视为超出范围。

-Wswitch-bool
警告在GCC文档中进行了描述(重点是我的):

每当

switch
语句具有布尔类型索引并且 case 值超出布尔类型的范围。有可能 通过将控制表达式转换为类型来抑制此警告 除了布尔值之外。

要涵盖所有三种情况,您可以使用不同的比较表达式:

switch ((m > n) - (m < n)) {
    case -1: // m < n
    case  1: // m > n
    case  0: // m == n
}

2
投票

这是一种你应该只用 if 语句来解决的问题,但如果你设置使用 switch case:你的检查只能告诉你变量 m 是否大于 n,而不是它们是否相等。如果 m 较大,

switch ((m > n) + (m >=n))
将为您提供 2,如果它们相等,则为 1,如果 n 较大,则为 0。


0
投票
#include<stdio.h>

//function prototype
int comp(int x, int y);

//Function Declaration
int comp(int x, int y)
{
    if(x>y)
    {
        return 1;
    }
    else if(x==y)
    {
        return -1;
    }
    else 
        return 0;
}

//main function
int main()
{
    int m,n,result;
    printf("Enter 1st number: ");
    scanf("%d",&m);
    printf("Enter 2nd number: ");
    scanf("%d",&n);

    result=comp(m,n); //function call and catch in the result

    switch(result)
    {
        case 1:
            printf("1st number is greater than the 2nd number");
            break;  
        case 0:
            printf("2nd number is greater than the 1st number");
            break;
        case -1:

            printf("Both numbers are equal");
            break;
    }
    return 0;
}
© www.soinside.com 2019 - 2024. All rights reserved.