Created
October 29, 2014 05:03
-
-
Save windymelt/9d30a56871cda86bdfbf to your computer and use it in GitHub Desktop.
数値判定
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
/* 定数定義 */ | |
#define CHAR_ZERO 0x30 | |
#define CHAR_ONE 0x31 | |
#define CHAR_NINE 0x39 | |
#define CHAR_NULL 0x00 | |
/* cが0から9までのcharのとき真 */ | |
int isZeroToNine(char c) { | |
return c >= CHAR_ZERO && c <= CHAR_NINE; | |
} | |
/* cが1から9までのcharのとき真 */ | |
int isOneToNine(char c) { | |
return c >= CHAR_ONE && c <= CHAR_NINE; | |
} | |
int main (int argc, char* argv[]) { | |
/* 引数がないときは失敗する */ | |
if(argc == 1) {return 1;} | |
char* firstParam = argv[1]; | |
int isNumber = 0; | |
for(int argv_i = 0; firstParam[argv_i] != 0; argv_i++) { | |
/* 第一引数の長さが1文字分であるとき */ | |
/* 文字列が1文字のとき文字列のサイズはNULL文字を含めてchar 2つ分になる */ | |
if (argv_i == 0 && sizeof(firstParam) == (sizeof(CHAR_ONE) + sizeof(CHAR_NULL))) { | |
/* 1文字だけのとき */ | |
/* 「0」を含める */ | |
isNumber = isZeroToNine(firstParam[0]); | |
} else if (argv_i == 0) { | |
/* 複数文字で先頭文字のとき */ | |
/* 先頭が0の文字列は数値とみなさない */ | |
isNumber = isOneToNine(firstParam[0]); | |
} else { | |
/* 複数文字のときで先頭でない文字*/ | |
/* &=を利用して論理積を重ねる */ | |
/* 全ての文字で条件をクリアしたときのみisNumberは1になる */ | |
isNumber &= isZeroToNine(firstParam[argv_i]); | |
} | |
} | |
if (isNumber == 0) { | |
printf("Not a number\n"); | |
} else { | |
printf("It's a number\n"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment