的使用


轉載:

1.https://www.cnblogs.com/jediael/archive/2013/02/03/4304259.html

2.https://zhidao.baidu.com/question/561939817.html

 

(1)使用了<stdbool.h>后,可使用true和false來表示真假。

(2)在循環語句中進行變量聲明是C99中才有的,因此編譯時顯式指明 gcc -std=c99 prime.c

[lujinhong@lujinhong chapter9]$ gcc prime.c
prime.c: In function ‘isPrime’:
prime.c:23: error: ‘for’ loop initial declarations are only allowed in C99 mode
prime.c:23: note: use option -std=c99 or -std=gnu99 to compile your code
[lujinhong@lujinhong chapter9]$ gcc -std=c99 prime.c

 

 

/**********************************************************
*purpose:
*       判斷一個整數是否素數。
*method:
*       從2開始,至這個整數的平方根,若能整除其中任何一個則非素數並返回。
***********************************************************/


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

bool isPrime(int n);

int main(void){

    int n;

    printf("Please enter a digit to test is it a prime or not: ");
    scanf("%d",&n);
    if(isPrime(n))
        printf("%d is a prime.\n", n);
    else
        printf("%d is not a prime.\n", n);

    return 0;
}


bool isPrime(int n){

    for(int i=2; i*i<n; i++){
        if(n%2==0) return false;
    }
    return true;
}





bool 是C++中的關鍵字,C中不支持
所以C99標准中百引入了頭文件 stdbool.h,包含了四個用度於布爾型問的預定義宏
#define true 1
#define false 0
#define bool _Bool
typdef int _Bool
看看 stdbool.h 的內容就知道了。

is_even函數是用來判斷你輸入的整數是否是偶版數權。如果是則返回true,否則返回false
如:輸入10返回true 11返回false
10是偶數,11是奇數




免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM