전공/C

과제 1 - variable (1 ~ 5)

yha97 2021. 6. 21. 11:22

맨 처음 C 언어 과제를 풀면서 어려워 했던 마음을 기록하자는 의미로 작성합니다.

 

기본 개념은 구글에 많이 나와 있으므로 생략하며 과제의 기록 의미로 글을 작성합니다.

 

 

주어진 샘플인 43267에 따라 시, 분, 초로 나누어 출력하는 프로그램입니다.

 

#include <stdio.h>

int main(){
	int time, t, h, m, s;
	time = 43267; // given time
	
	h = time/3600; // divide with hours in seconds
	time %= 3600; // set time without hours
	m = time / 60; // divide with minutes in seconds
	time %= 60; // set time without hours
	s = time; // set time with seconds
	
	printf("43267 seconds is %d hours %d minutes %d seconds\n", h, m, s); // prints results
	return 0;
}

시간을 설정하였고, 시 -> 분 -> 초 순서로 나누어 연산, 출력하였습니다.

(시 : 3600초, 분 : 60초)

 

* % 연산차 참고(modular)

 

 

시간, 속력, 거리를 주어진 샘플에 따라 계산, 출력하는 프로그램입니다.

 

#include <stdio.h>

int main(){
	int t, d, v;
	
	d = 60 * 1000; // distance is 60km
	v = 30 * 1000; // velicity : 30km per hour
	t = d / v * 60; // due to calculating with minutes, it is multiplied with 60
	printf("a cat spent %d minutes\n", t);
	
	return 0;
}

거리 = 속력 * 시간 <-- 이 공식을 잘 활용하여 출력하면 됩니다.

 

 

정해진 샘플값을 단위에 따라 변형하여 출력하는 프로그램입니다.

 

#include <stdio.h>

int main(){
	double h, w; // h : height, w : weight
	double bmi;
	
	// inputs height and weight
	printf("Please input your Height: ");
	scanf("%lf", &h);
	h = h * 0.01; // convert centimeter into meter
	printf("Please input your Weight: ");
	scanf("%lf", &w);
	
	bmi = w / (h * h); // calculating BMI
	
	printf("Your BMI index is %.2f\n", bmi); // printing result
	return 0;
}

소수점 표현을 위해 double형으로 설정하여 출력하였습니다.

 

double형으로 입력받기 때문에 scanf에서 %lf형으로 받았습니다.

 

이전부터 %lf, %f와 헷갈려서 처음에 코드를 작성할 때 %f으로 했더니 값이 이상하게 나오길래 구글링을 한 결과 %f는 float형으로 입력할 경우에 사용하는 입력변수라는 것을 알게 되었습니다.

 

아마 이 이후에는 계속 double형으로 문제를 풀었던 것 같네요ㅎㅎ

 

 

int형 변수 height와 weight를 입력받은 후 계산한 값을 출력하는 프로그램입니다.

 

#include <stdio.h>

int main(){
	int h, w, result; // declares values in height, weight, result
	
	printf("Height: "); // inputs height
	scanf("%d", &h);
	printf("Weight: "); // inputs weight
	scanf("%d", &w);
	
	result = h - w; // calculating result
	
	printf("Height - Weight = %d\n", result); // prints
	return 0;
}

int형 변수 h, w, result를 선언, height와 weight를 입력받고 난 후 계산 및 출력하였습니다.

 

이해하는데 큰 어려움은 없을 것입니다.

 

키와 몸무게를 입력받은 후 이에 해당하는 BMI를 출력하는 프로그램입니다.

 

#include <stdio.h>

int main(){
	double h, w; // h : height, w : weight
	double bmi;
	
	// inputs height and weight
	printf("Please input your Height: ");
	scanf("%lf", &h);
	h = h * 0.01; // convert centimeter into meter
	printf("Please input your Weight: ");
	scanf("%lf", &w);
	
	bmi = w / (h * h); // calculating BMI
	
	printf("Your BMI index is %.2f\n", bmi); // printing result
	return 0;
}

BMI 출력을 실수형으로 출력해야 하는 관계로 double형으로 입력받았습니다.

 

height와 weight를 입력받은 이후 계산 및 출력하는 프로그램입니다.

 

height에서의 단위변환을 하지 않아 값이 비정상적으로 크게 나왔던 기억이 있습니다.

 

문제에 나온 대로 연산 및 출력한다면 풀 수 있을 것입니다.