1. 程式人生 > >C++學習之二三種方法判斷奇偶數

C++學習之二三種方法判斷奇偶數

#include <iostream>
#include"stdlib.h"
//#include<cmath>
using namespace std;

int main()
{
    //---------------first method
    // Basially even numbers are those whice are divisible by 2,and Odd number
    //are those which numbers are not divisible by 2
//    int num;
//    cout<<"請輸入任意整數"<<endl;
// cin>>num; // if(num%2==0){ // cout<<"是個偶數"<<endl; // } // else{ // cout<<"是個奇數"<<endl; // } //----------------second method //using ternary or conditional operator // int number; // cout<<"Enter any number:"; // cin>>number; // (number%2==0)?cout<<" Even number":cout<<"Odd number";
// --------------------thrid method // check if the given number is Even or Odd Using Bitwise Operator // and與運算,兩個數同為1才是1,隨便一個奇數轉為二進位制後最後一位 //一定是1,所以奇數與1做與運算結果肯定是1,位運算執行效率較高 int number; cout<<"Enter any number:"; cin>>number; if(number&1) { cout<<number<<"Odd number"
; } else { cout<<number<<"Even number"; } system("pause"); return 0; }