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;
}