演習3-4 K&R プログラミング言語C

演習3-4

int の有効範囲を調べる。

#include <stdio.h>
#include <limits.h>

int main(int argc, char *argv[])
{
    printf("INT_MIN => %12d\n", INT_MIN);
    printf("INT_MAX => %12d\n", INT_MAX);

    return 0;
}

INT_MIN の符号を反転させると INT_MAX を超えてしまう。

$ ./intsize
INT_MIN =>  -2147483648
INT_MAX =>   2147483647

値が正の場合と負の場合とで処理を分けて対処する。

#include <stdio.h>
#include <limits.h>
#include <string.h>

#define MAX 1024

void itoa(int n, char s[]);
void reverse(char s[]);

int main(int argc, char *argv[])
{
    char str[MAX];
    int n;

    n = INT_MIN;
    itoa(n, str);
    printf("%s\n", str);

    return 0;
}

void itoa(int n, char s[])
{
    int i;

    i = 0;
    if (n >= 0) { /* 0 または正の場合 */
        do {
            s[i++] = n % 10 + '0';
        } while ((n /= 10) > 0);
    } else { /* 負の場合 */
        do {
            s[i++] = ((n % 10) * -1) + '0';
        } while ((n /= 10) < 0);
        s[i++] = '-';
    }

    s[i] = '
#include <stdio.h>
#include <limits.h>
#include <string.h>

#define MAX 1024

void itoa(int n, char s[]);
void reverse(char s[]);

int main(int argc, char *argv[])
{
    char str[MAX];
    int n;

    n = INT_MIN;
    itoa(n, str);
    printf("%s\n", str);

    return 0;
}

void itoa(int n, char s[])
{
    int i;

    i = 0;
    if (n >= 0) { /* 0 または正の場合 */
        do {
            s[i++] = n % 10 + '0';
        } while ((n /= 10) > 0);
    } else { /* 負の場合 */
        do {
            s[i++] = ((n % 10) * -1) + '0';
        } while ((n /= 10) < 0);
        s[i++] = '-';
    }

    s[i] = '\0';
    reverse(s);
}

/* reverse : 文字列 s をその位置で逆順にする */
void reverse(char s[])
{
    int c, i, j;

    for (i = 0, j = strlen(s) - 1; i < j; i++, j--) {
        c = s[i];
        s[i] = s[j];
        s[j] = c;
    }
}
'
; reverse(s); } /* reverse : 文字列 s をその位置で逆順にする */ void reverse(char s[]) { int c, i, j; for (i = 0, j = strlen(s) - 1; i < j; i++, j--) { c = s[i]; s[i] = s[j]; s[j] = c; } }

実行結果

$ ./ex3-4
-2147483648
プログラミング言語C 第2版 ANSI規格準拠
B.W. カーニハン D.M. リッチー
共立出版
売り上げランキング: 9726
«
»