쉽게 풀어쓴 C언어 EXPRESS(개정 3판) - Chapter 9-1
1.
#include <stdio.h>
int add(int, int);
int sub(int, int);
int mul(int, int);
int div(int, int);
int main(void) {
char op;
int x, y;
int i;
for (i = 0; i < 10; i++) {
printf("연산을 입력하시오: ");
scanf("%d %c %d", &x, &op, &y);
if (op == '+')
printf("연산 결과: %d \n", add(x, y));
else if (op == '-')
printf("연산 결과: %d \n", sub(x, y));
else if (op == '*')
printf("연산 결과: %d \n", mul(x, y));
else if (op == '/')
printf("연산 결과: %d \n", div(x, y));
else
printf("지원되지 않는 연산자입니다. \n");
}
return 0;
}
int add(int x, int y) {
static int count;
count++;
printf("덧셈은 총 %d번 실행되었습니다.\n", count);
return (x + y);
}
int sub(int x, int y) {
static int count;
count++;
printf("뺄셈은 총 %d번 실행되었습니다.\n", count);
return (x - y);
}
int mul(int x, int y) {
static int count;
count++;
printf("곱셈은 총 %d번 실행되었습니다.\n", count);
return (x * y);
}
int div(int x, int y) {
static int count;
count++;
printf("나눗셈은 총 %d번 실행되었습니다.\n", count);
return (x / y);
}
2.
#include <stdio.h>
#include <stdlib.h>
void get_dice_face();
int main(void) {
int i;
for (i = 0; i < 1000; i++)
get_dice_face();
return 0;
}
void get_dice_face() {
static int one, two, three, four, five, six;
int face;
face = rand() % 6;
if (face == 0) one++;
else if (face == 1)
two++;
else if (face == 2)
three++;
else if (face == 3)
four++;
else if (face == 4)
five++;
else
six++;
printf("%d %d %d %d %d %d\n", one, two, three, four, five, six);
}
3.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int get_random() {
static int inited = 0;
if (inited == 0) {
printf("초기화 실행\n");
srand((unsigned)time(NULL));
inited = 1;
}
return rand();
}
int main(void) {
printf("%d\n", get_random());
printf("%d\n", get_random());
printf("%d\n", get_random());
return 0;
}
4.
#include <stdio.h>
double recursive(int n) {
if (n == 1)
return 1;
else
return 1.0 / n + recursive(n - 1);
}
int main(void) {
printf("%f\n", recursive(10));
return 0;
}
댓글
댓글 쓰기