简体   繁体   English

布尔数据类型随机整数

[英]boolean data type random integer

Im trying to create a random number generator and judging the random integers odd or even using a srand call and boolean but i cant figured out how to get it to distinguish properly between whats odd and whats even. 我试图创建一个随机数生成器并使用srand call和boolean判断随机整数奇数或什至偶数,但我无法弄清楚如何正确地区分奇数和偶数。

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>

int i;
int num1;
int num2;

bool isOdd (int num1, int num2);

int main(void)
{
srand(time(NULL));


for (i=1; i <= 10; ++i) {
 num1 = rand() % 10 + 1;
 num2 = rand() % 10 + 1;
printf("The two random numbers are %u and %u\n", num1, num2);


bool valueIsOdd = isOdd(num1, num2);

if (valueIsOdd) {
    printf("one of these numbers, %u and %u, isOdd.\n\n", num1, num2);
}
else {
    printf("Both of these numbers, %u and %u, are even.\n\n", num1, num2);
    }
}
}

bool isOdd(int num1, int num2)
{
if (num1 % 2 != 0) {
    return true;
}
else {
    return false;
    }

}

You are only checking one number in the function isOdd . 您仅在函数isOdd检查一个数字。 You need to check both numbers. 您需要检查两个数字。

if ((num1 % 2 != 0) || (num2 %2 !=0)) {
   return true;
}
else {
   return false;
}

Or, you can check for both even and make the code a bit cleaner. 或者,您可以同时检查两者,并使代码更简洁。

if ((num1 % 2 == 0) && (num2 %2 ==0)) {
   return false;
}
else {
   return true;
}

I understand your question. 我明白你的问题。 u are asking that to differentiate from the two number which is odd right. 您要求将其与两个数字区分开来,这是对的。 The main purpose of the bool is to represent either 1 or 0 why to use char consists of 8 bits. 布尔的主要目的是表示1或0,为什么使用char由8位组成。 If u want to check 1 number use bool datatype. 如果您想检查1个数字,请使用bool数据类型。 Otherwise if u want to know two number of all possible results better go with char datatype. 否则,如果您想知道所有可能结果中的两个,最好使用char数据类型。

Here u have two numbers.4 possibility. 在这里,您有两个数字。4。

        number 1         number 2
1         odd              even
2         even             odd
3         even             even
4         odd              od


         if ((num1 % 2 != 0) && (num2 % 2 == 0)) {
                return 1;
         }
        else if ((num1 % 2 == 0) && (num2 % 2 != 0)) {
                return 2;
        }
        else if ((num1 % 2 == 0) && (num2 % 2 == 0)) {
                return 3;
        }
        else {
           return 4;
        }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM