<C프로그래밍-새내기를 위한 첫 C 언어 책>연습문제 chapter 8 (1,2,3,4,5)

1. 배열에 저장된 값 중 사용자가 입력한 값이 몇 개 들어 있는지 표시하려고 한다. 이 프로그램에서 밑줄 친 곳에는 무언가가 생략되어 있거나 에러가 난다. 잘못된 이유와 어떻게 수정해야 하는지 적으시오.

 

#include <stdio.h>
#define N 30
void print_title();

void main()
{
    int result[N] = { ... };
    int count, i, target;
    scanf("%d", &target);
    print_title;
    count = frequency(result[N], target);

    return 0;
}

void print_title()
{
    ...
}

int frequency(int arr[N], value)
{
    ...

}

void main() : 함수 내에서 0을 반환하는데 반환 값이 void형으로 지정되어 있다. 반환형을 int로 지정해야 한다.

print_title; : 괄호를 생략했다. print_title()로 함수를 호출해야 한다.

count = frequency(result[N], target); :배열이 아니라 배열 요소를 전달했는데, 배열의 크기는 30이므로 마지막 인덱스는 29번이다. 잘못된 주소를 호출했다.

int frequency(int arr[N], value) : 반환 값이 int형으로 지정되어 있는데 실제로 반환된 값은 없다. 함수 정의가 호출보다 뒤에 있으므로 에러가 난다. main 상단에 원형을 선언해야 한다.


2. 다음 식을 예와 같이 C 언어에 맞게 표현하시오.

 

예: $y=2^{10}$ -> y = pow(2,10)

$y=e^{x} + e^{-x}$ -> y = exp(x) + exp(-x)

$y= \ln 3x + \log_{10}x$ -> y = ln(3x) + log10(abs(x))

$y = \sin(90) + \cos(180)$ -> y = sin(90) + cos(180)

$y = \sqrt{b^{2}-4ac}/2a$ -> y = sqrt(pow(b,2)-4*a*c) / 2*a


3. 다음 프로그램을 실행했을 때 9행에서 convert 함수가 호출되어 반환 값이 전달된 직후 10행에서의 second값을 적으시오.

 

#include <stdio.h>
int convert(int second);

int main(void)
{
    int second;

    second = 5000;
    int hour = convert(second);
    printf("%d초는%d시간", second, hour);

    return 0;
}

int convert(int second)
{
    second = second / 60;
    second = second / 60;
    return second;
}

convert 함수에서 바뀐 second값은 main 함수에 영향을 주지 않으므로 10행에서의 second값은 5000이다.


4. 1feet는 30.48cm다. cm 단위의 키를 height 변수에 입력받은 후 feet 단위로 변환하여출력하도록 다음 프로그램을 완성하시오.

 

#include <stdio.h>
//cm_to_feet 함수의 원형 선언
double cm_to_feet(double hei);

int main(void)
{
	double height;

	printf("당신의 키는(cm)");
	scanf("%lf", &height);

	printf("키 %.1lf cm는 %.1lf feet입니다.", height, cm_to_feet(height));

	return 0;
}

//cm_to_feet 함수의 정의
double cm_to_feet(double hei)
{
	return hei / 30.48;
}

5. 사용자의 키(height)와 몸무게(weight)를 입력받아 입력된 키에 해당하는 체중이 표준체중보다 초과인지, 미달인지, 같은지를 다음과 같이 출력하는 프로그램을 작성하시오. 표준체중은 (키-100)*0.9이며, 표준체중과의 차이 즉(표준체중-사용자의 체중)은 difference 함수를 이용해 구한다. 단 표준체중과의 차이는 0,1 미만일 때는 0을 반환하도록 한다. 표준체중과의 차이가 0.01일 때는 '0.0kg 초과'로 출력되는 것을 막기 위해서다.

 

#include <stdio.h>

double difference(double std, double wei);

int main(void)
{
	double height, weight, std_weight;

	printf("키는?: ");
	scanf("%lf", &height);
	printf("몸무게는?: ");
	scanf("%lf", &weight);
	
	std_weight = (height - 100) * 0.9;

	printf("=======================================================\n");
	printf("키가 %.1lfcm인 사람의 표준 체중 %.1lfkg", height, std_weight);
	difference(std_weight, weight);
	return 0;
}

double difference(double std, double wei)
{
	double dif = std - wei;
	if (dif < 0.1)
		dif = 0;
	if (dif > 0)
		printf("보다 %.1lfkg 미달", dif);
	else if (dif < 0)
		printf("보다 %.1lfkg 초과", -dif);
	else
		printf("과 동일");
}