C言語なら俺に聞け(入門篇) Part 26
at TECH
278:デフォルトの名無しさん
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
5379日前に更新/199 KB
担当:undef