2009年12月7日 星期一

轉換整數型態 atoi(word)

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

int main()
{
    int x;
    char word[30]; //最多只能讀30個字母組成的單字

    while(1)
    {
        printf("\nEnter any number:");
        //scanf("%d/n",&x);
        //為了因應使用者可能輸入帶有字元的變數,
        //因此改用字串接收輸入,然後再利用 atoi 將字串轉為整數
        scanf("%s",word);
        // 呼叫 atoi()將字串轉為整數
        x=atoi(word);

        if(x<=50 && x>0)
        {
            printf("%d is >0 and <= 50",x);
        }
        else if(x<=100 && x>50)
        {
            printf("%d is >50 and <= 100",x);
        }
        else if(x>100)
        {
            printf("%d is >100",x);
        }
        else
        {
            printf("%d is <=0 or not integer",x);
        }
    }
    return 0;
}

沒有留言:

張貼留言