C言語なら俺に聞け(入門篇) Part 26at TECH
C言語なら俺に聞け(入門篇) Part 26 - 暇つぶし2ch278:デフォルトの名無しさん
08/04/09 23:10:17
>>275
>また、こうすればもっと判りやすくできるなどあったら教えて欲しいです;
うまく関数化しよう。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int absolute(int n1, int n2) { return n1>n2 ? n1-n2 : n2-n1; }
void check(const char* s)
{
    int i;
    for(i=0; s[i]; i++) {
        if( !isdigit(s[i]) && s[i]!='-' ) { puts("不正な文字"); exit(EXIT_FAILURE); }
    }
    if(!s[0] || strcmp(s, "-")==0) { puts("数値ではない"); exit(EXIT_FAILURE); }
}
int input(void)
{
    char str[100];
    scanf("%99s", str); check(str); str[ str[0]=='-' ? 9 : 8 ] = 0; return atoi(str);
}
int main(void)
{
    int a, b;
    printf("数値a="); a=input();
    printf("数値b="); b=input();
    printf("%dと%dの差の絶対値は%d\n", a, b, absolute(a,b));
    return 0;
}


次ページ
続きを表示
1を表示
最新レス表示
レスジャンプ
類似スレ一覧
スレッドの検索
話題のニュース
おまかせリスト
オプション
しおりを挟む
スレッドに書込
スレッドの一覧
暇つぶし2ch