查找偶数/奇数,而不使用数学/按位运算符 [英] Find Even/Odd number without using mathematical/bitwise operator

查看:162
本文介绍了查找偶数/奇数,而不使用数学/按位运算符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近被要求编写一个程序,它决定一个数字是偶数还是奇数,而不使用任何数学/位运算符!



任何想法? >

谢谢!

解决方案

这可以使用1位字段

 #include< iostream> 

struct OddEven {
unsigned a:1;
};
int main(){
int num;
std :: cout<<输入数字:;
std :: cin>> num;
OddEven obj;
obj.a = num;
if(obj.a == 0)
cout<<Even!;
else
cout<<Odd!;
return 0;
}

由于obj.a是单字段值,举行那里!你可以检查你的答案.. 0 - >即使其他奇数.. !!


I was recently asked to write a program, that determines whether a number is even or odd without using any mathematical/bitwise operator!

Any ideas?

Thanks!

解决方案

This can be done using a 1 bit field like in the code below:

#include<iostream>

struct OddEven{
    unsigned a : 1;
};
int main(){
    int num;
    std::cout<<"Enter the number: ";
    std::cin>>num;
    OddEven obj;
    obj.a = num;
    if (obj.a==0)
        cout<<"Even!";
    else
        cout<<"Odd!";
    return 0;
}

Since that obj.a is a one-field value, only LSB will be held there! And you can check that for your answer.. 0 -> Even otherwise Odd..!!

这篇关于查找偶数/奇数,而不使用数学/按位运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆