開発環境
- OS X Lion - Apple(OS)
- Emacs、BBEdit - Bare Bones Software, Inc. (Text Editor)
- プログラミング言語: C
- Clang (コンパイラ)
プログラミング言語C 第2版 ANSI規格準拠 (B.W. カーニハン D.M. リッチー (著)、 石田 晴久 (翻訳)、共立出版)の第3章(制御の流れ)3.6(ループ (do-while))の演習3-6を解いてみる。
その他参考書籍
- プログラミング言語Cアンサー・ブック 第2版 (クロビス・L.トンド、スコット・E.ギンペル(著)、矢吹 道郎(翻訳))
演習 3-6.
コード
sample.c
#include <stdio.h>
#include <string.h>
#define MAXLINE 1000
void itoa(int, char s[], int);
int main()
{
int n, m, cols;
char s1[MAXLINE], s2[MAXLINE],
s3[MAXLINE], s4[MAXLINE];
n = 12345;
m = 1234567890;
cols = 20;
itoa(n, s1, cols);
itoa(m, s2, cols);
itoa(-n, s3, cols);
itoa(-m, s4, cols);
printf("%s\n%s\n%s\n%s\n", s1, s2, s3, s4);
return 0;
}
void itoa(int n, char s[], int cols)
{
int i, sign;
void reverse(char s[]);
sign = n;
i = 0;
do {
s[i++] = (n < 0 ? -(n % 10): n % 10) + '0';
cols--;
} while ((n /= 10) != 0);
if (sign < 0) {
s[i++] = '-';
cols--;
}
while (cols > 0) {
s[i++] = ' ';
cols--;
}
s[i] = '\0';
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;
}
}
入出力結果(Terminal)
$ ./a.out
12345
1234567890
-12345
-1234567890
$
0 コメント:
コメントを投稿