如何使用&&在if语句中

时间:2017-11-19 09:40:06

标签: c

我的节目如下。

我想改变这一行:

if(a==b || b==c)

使用&&代替||

#include <stdio.h>
int main()
{
    int digit, a, b, c;
    scanf("%d", &digit);
    a=digit/1000;
    b=digit/100%10;
    c=digit/10%10;
    if(a==b || b==c) // how to use && in this program
        printf("YES");
    else
        printf("NO");
    return 0;
}

2 个答案:

答案 0 :(得分:2)

由于您正在检查所有数字是否相同,因此您的问题中存在错误。 if((a==b) || (b==c))如果两个输入中的任何一个相同,它将打印 YES 。你不想要那个。

所以使用&amp;&amp;这个等式只是

if((a == b) && (b == c))

多数民众赞成。我之前刚刚转换了你的错误。 你还必须减少你的号码

a = digit % 10;
digit = digit / 10;
b = digit % 10;
digit = digit / 10;
c = digit % 10;

并且不减少数量也可以完成

a = digit / 100;
b = digit / 10 % 10;
c = digit % 10;

答案 1 :(得分:1)

如果一个数字包含三位数,则可以使用表达式number % 10number / 10 % 10和最后number / 100或更好number / 100 % 10来计算数字。

所以你应该写

int number, a, b, c;

//...

a = number % 10;
b = number / 10 % 10;
c = number / 100 % 10;

if ( a == b && b == c ) { /*...*/ }
else { /*...*/ }

然而这种做法并不好。用户可以输入仅包含一个数字或多于三个数字的数字。

您可以使用一般方法,而不是使用三位数的部分数字。

下面是一个演示程序,展示了如何完成它。

#include <stdio.h>

int main( void )
{
    const unsigned int Base = 10;

    while ( 1 )
    {
        printf("Enter a non-negative number (0 - exit): ");

        unsigned int number;

        if (scanf("%u", &number) != 1 || number == 0) break;

        unsigned int digit = number % Base;

        while ((number /= Base) && (number % Base == digit)) digit = number % Base;

        if ( number == 0 )
        {
            printf("All digits of the number are the same and equal to %u\n", digit);
        }
        else
        {
            printf("Digits of the number are not equal each other\n");
        }
    }

    return 0;
}

它的输出可能看起来像

nter a non-negative number (0 - exit): 111
All digits of the number are the same and equal to 1
Enter a non-negative number (0 - exit): 211
Digits of the number are not equal each other
Enter a non-negative number (0 - exit): 0
相关问题