728x90

개요

난 이론적인 것으로는 효율적으로 배우지 못하는 유형의 사람이다.

주어진 숙제하는 걸 제일 재미없어하고 내 상상력을 발휘할 수 있는 것들을 좋아하는 사람.

 

그래서 이론적으로 별 뽑는 과제나 만들라는 프로그램 만드는 게 제일 하기 귀찮다.

(물론 어쩔 수 없이 하다 보면 재밌긴 하다)

그래서 다음 주 자바 시험이 있는 나는 어쩔 수 없이 공부는 해야겠는데

그냥 공부하는 건 너무 재미없으니까 앱을 개발하기로 했다.

 

마침 최근 홍콩 미식 단톡방을 보고 한식 맛집 지도가 있었으면 좋겠다는 생각을 하던 참이었으니까.

 

 

최근 블로그 맛집 포스팅을 하면서 이걸 어떻게 더 유명하게 만들 수 있을까를 생각하다가 한국 식당 전문으로 하는 맛집 앱이 없다는 걸 깨달았다.

 

최근 봉루와 ㅇㅂㅍ의 리뷰를 하면서 둘을 비교해 봤는데, 맛집 비교를 하려면 일일이 하나하나 검색해서 비교해야 하는 부분이 꽤나 비효율적이라고 생각했다.

 

심지어 위치를 알고 싶을 때도 일일이 지도에 검색하거나 맛집 리뷰에 적힌 위치를 찾아야 한다.

 

여러 맛집 중 가까운 곳을 가고 싶을 땐 일일이 지도에 검색해가며 비교해야 한다.

 

 

너무 귀찮지 않나?

 

물론 나와 비슷한 생각을 해서 맛집 지도 앱이 이미 개발된 걸로 알지만, 한국 맛집 전문으로 리뷰까지 올려놓고 비교하는 맛집 지도는 없는 거로 안다.

 

적어도 홍콩에서 유명하진 않다.

안 유명하니까 저렇게 홍콩 미식 오픈 채팅방에 계속 '여기 어때요?' 같은 질문이 올라오지.

 

 

그래서 자바로 안드로이드 앱을 개발해 보려고 한다.

시험 기간이니까 일단은 시험 전까지 해야겠고... 그럼 이틀 만에 대충 구조는 완성해야겠다.

 

안드로이드 앱? 사실 코틀린 쓰는 게 더 편하다.

 

근데 난 자바 시험이 있으니 자바로 개발해야지.

 


개발 환경

 

1. 개발 언어: JAVA

  • 앞전에서 설명했듯이 난 자바 시험 때문에 이걸 만드는거다.
  • 여러분은 꼭 코틀린으로 만들어라...! 

2. DB: Google Firebase > cloud-hosted NoSQL database.

  • 사실 내가 1학년때 미리 들은 웹개발 수업에서 배운건 MongoDB다.
  • 근데 우리 팀원이 배운거로 안하고 firsbase를 들고와서 개발하길래 프로젝트는 이거로 했다.
  • 심지어 리포트에서 MongoDB 대차게 디스하길래 이거로 해보기로 했다... 

3. 서버: 아직 안정했다. 


어플 구상

 

1인개발. 그리고 서버와 디비연결 이외의 모든것을 하루만에 개발해야하는 (내일이 시험이다) 특성상

최대한 간단한 UI 로 적은 기능에 집중하기로 했다. 

 

<맛집추>

- 맛집 추천/리뷰 앱
- 구글 맵 api 기반
- 맵 위에 클릭이벤트 넣고 식당 좌표 표시
- 검색기능 
- 내 위치랑 거리 비교 (이건 나중에 넣을 예정)
- 뭔가 dijkstra라는걸 써보고싶은데 어떻게 써야될지 모르겠다. 이건 시간 많을때 하는거로...

ex) 
- 맵 위에 한식 맛집들이 표시되어있음
- 클릭 시 내 블로그 링크로 이동ㅎㅎㅎㅎㅎ 조회수개꿀
- 다른사람이 리뷰 추가하고싶으면 내 블로그에 댓글달게 만들고 db연결해서 앱에서 조회가능
- 검색기능. '탄소' 검색시 맵에서 탄소만 뜸
- 즐겨찾기 기능 (즐겨찾기 클릭하면 즐겨찾기한 맛집만 보임)
- 거리 비교 기능 (여러 곳 클릭하면 현재 위치와 거리 비교)
- 평점 비교 기능 (이건 나중에 유저 많아지면 추가)

 

 

어플 기능

최대한 한 페이지 내로 하는게 목표

- 메인 화면 구현
	- 메인화면 상단 검색창 구현
    	- 검색시 해당 식당으로 좌표 이동
        
    - 지도 위에 식당 표시
    - 식당 카테고리 검색 기능
728x90
728x90

 

랜딩 페이지란?

랜딩 페이지(landing page)는 검색 엔진, 광고 등을 경유하여 접속하는 이용자가 최초로 보게 되는 웹페이지이다. 

링크를 클릭하고 해당 웹페이지에 접속하면 마케터가 의도한 행위를 하도록 하는 페이지를 의미한다.

 

현재 진행하고있는 창업아이탬 GGOOMING 의 랜딩페이지를 제작하기 위해 이 프로젝트를 시작했다. 

GGOOMING 은 중고등학생의 자아인식을 도와주는 에듀테크 웹 플렛폼이다. 

사실 랜딩페이지라는것은 개발자 하나만 있어서 만들어질 수 있는게 아니다. 

정말 '랜딩페이지' 의 효과를 보고싶다면 우리는 랜딩페이지에 사람들을 끌어모을 수 있는 마케터, 유저의 관심을 끌어줄 UI  UX 디자이너, 그리고 개발자가 필요하다. 

 

좀 더 세분화하자면 

개발자에도 '프론트엔드'와 '백엔드' 개발자가 필요한데,

프론트엔드는 눈에 보이는 웹사이트의 모양을, 백엔드는 웹사이트를 사람들에게 보이도록 서버를 잡아주는 역할을 한다. 

 

이 글은 프론트엔드 개발자 지망생으로써의 랜딩페이지 제작기이다.

 

1. 기존 랜딩페이지 분석 

제작하기 전, 기존 랜딩페이지들을 html 구조적 관점으로 분석해서 가장 보편적인 디자인을 선택할 것이다. 

우리가 개발하고자하는 GGOOMING은 웹 플랫폼이기에, 다른 웹 어플리케이션들이 어떤 방식으로 앤딩페이지를 제작하였는지 분석해볼 것이다. 

 

요즘 tech 기반 유니콘 기업들이 많다. 

한국에는 23개의 유니콘 기업들이 있는데, 이중 tech 기반 기업들의 랜딩페이지를 분석해보자.

 

https://docs.google.com/spreadsheets/d/1kgtRAZQYZh5iIjf-FzfkiOXCY_5T0EkcASX_dyx2Dds/edit#gid=0

랜딩페이지가 홈페이지의 첫 페이지에 있는 경우가 많았다.

딱 한장짜리 랜딩페이지는 토스와 배달의민족 뿐이였다. 

다른 기업들도 분석해 보았더니 (스프레드시트 참조) 대표적인 랜딩페이지의 구조는 다음과 같았다.

 

이 구조에서 article 부분이 여러번 반복된 형태를 지니고 있었다. 

 

2. 랜딩페이지 HTML구조 제작과정

분석한 랜딩페이지의 구조는 Web application 강의에서 과제로 만들었던 내 광기의 웹사이트와 매우 유사했다. 

내 웹사이트 또한 <nav> 요소가 상단에 가로로 자리잡고 있었고,

href="#~" 을 사용해서 클릭할 시 한 페이지에서 다른 section 으로 이동할 수 있게 만들어져 있었다. 

 

이 웹사이트를 만들때 나는 깔끔함을 그다지 신경쓰지 않았기에, 코드가 다소 난잡했다. 

 

 

웹페이지의 html 코드:

더보기

 

<!DOCTYPE html>
<html lang="en"><head>

	<link rel="shortcut icon" href="picture/1.jpg">
    <title>
        Emily's Website
    </title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384- 1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
    <link rel="preconnect" href="https://fonts.googleapis.com">

	<link rel="stylesheet" href="dark.css" media="(prefers-color-scheme: dark)" />
	<link rel="stylesheet" href="style.css" media="(prefers-color-scheme: light)"/>

    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Gloria+Hallelujah&family=Mochiy+Pop+P+One&display=swap" rel="stylesheet">
	<script src="action.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
	<script src="https://cdn.jsdelivr.net/npm/popper.js@1.14.7/dist/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
	<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</head>
<body onload="loadfile()">
	

<article>
	
<header class="container" id="befhover"  >
	<div class="headertext">
		<h1>I'm <span>Juhee Hur</span></h1>
		<h4>Broad-based engineering year 1 student</h4>
	</div>


</header>

<nav class="navbar" >
	<ul id="navigation">
		<li><a href="#about">About</a></li>
		<li><a href="#courses">Courses</a></li>
		<li><a href="#links">Links</a></li>
		<li><a onclick="special()">Special!</a></li>
		<li><a href="#links">Comment</a></li>
	</ul>

	
	<div class="burger" onclick="menuclick()">
		<div class="line1"></div>
		<div class="line2"></div>
		<div class="line3"></div>
	</div>

	<div class="btn-group" id="special">
		<button onclick="align()" style="width:33.3%">Align</button>
		<button onclick="newhobby()" style="width:33.3%">New Hobby</button>
		<button onclick="scrollhide()" style="width:33.3%">Scroll</button>
	</div>

</nav>




<div class="sticky">
<div class="progress-container" id="progressbar">
    <div class="progress-bar" id="myBar"></div>
</div>
</div>



<section id="about">
	<h2 id="header">All About Me</h2>
	<p>
	<picture>
		<div class="crop">
			<div id="bigscreen">
				<img style="width: 250px; height: 250px; object-fit: cover;" src="picture/Juheehur.jpg">
				<img style="width: 250px; height: 250px; object-fit: cover;" src="picture/hk.jpg">
				<img style="width: 250px; height: 250px; object-fit: cover;" src="picture/hongkong.jpg">
				<img style="width: 250px; height: 250px; object-fit: cover;" src="picture/world.jpg">
			</div>
			
			<div class="w3-content w3-display-container" id="slideshow" >
				<img class="mySlides" style="width: 250px; height: 250px; object-fit: cover;" src="picture/Juheehur.jpg" >
				<img class="mySlides" style="width: 250px; height: 250px; object-fit: cover;"src="picture/hk.jpg" >
				<img class="mySlides" style="width: 250px; height: 250px; object-fit: cover;"src="picture/hongkong.jpg" >
				<img class="mySlides" style="width: 250px; height: 250px; object-fit: cover;"src="picture/world.jpg">
			  
				<button class="w3-button w3-black w3-display-left" onclick="plusDivs(-1)">&#10094;</button>
				<button class="w3-button w3-black w3-display-right" onclick="plusDivs(1)">&#10095;</button>
			</div>
		
		</div>
	</picture>
	Hi I am Juhee Hur Student from Broad-based engineering at CUHK. I love studying languages (both real and programming) and aiming for computer science! 
	</p>


	<h3 id="header">My hobbies</h3>
	<div id="hobbies" class="flex-container">
		<div>Chess</div>
		<div>Sudoku</div>
		<div>Game</div>

	</div>
</section>

<section id="courses">
	<h2 id="header">My Courses</h2>
	<table>
		<tbody><tr>
			<th>Course code</th>
			<th>Contents</th>
			<th>Credits</th>
		</tr>
		<tr>
			<td>PHED1180</td>
			<td>Badminton</td>
			<td>1</td>

		</tr>
		<tr>
			<td>ESTR2160</td>
			<td>Building Web Applications</td>
			<td>3</td>
		</tr>
 		<tr>
			<td>CLCP1133</td>
			<td>Communication in Context I</td>
			<td>3</td>
		</tr>
		<tr>
			<td>CSCI1030</td>
			<td>Hands-ono Introduction to JAVA</td>
			<td>1</td>
		</tr>
		<tr>
			<td>ENGG1120</td>
			<td>Linear Algebra for Engineers</td>
			<td>3</td>
		</tr>
		<tr>
			<td>ENGG1130</td>
			<td>Multivariable Calculus for Engineers</td>
			<td>3</td>
		</tr>
		<tr>
			<td>SPAN1000</td>
			<td>Spanish I</td>
			<td>3</td>
		</tr>
	</tbody></table>
</section>

<section id="links">
	<h2 id="header">Interesting Links</h2>
	<ul>
		<li><a href="https://www.instagram.com/diatomic_carbon/" target="_blank">My instagram</a></li>
		<li><a href="https://diatomicc.tistory.com/" target="_blank">Programming learning website</a></li>
		<li><a href="https://comic.naver.com/artistTitle?artistId=319591" target="_blank">My comics</a></li>
		<li><a href="https://ogqmarket.naver.com/creators/%ED%83%84%EC%86%8C" target="_blank">My sticker market</a></li>
	</ul>
</section>

<section id="response">
	<h2 id="header">Response Web Design</h2>
	<ul>
		<p>These are the following changes when you look with your mobile screens</p>
		<li>Different form of navigation bar (horizontal for laptop and vertical for mobile)</li>
		<li>Adjusted length of special button bar</li>
		<li>mobile screen shows slideshow of pictures</li>
		<li>mobile screen shows all text aligned in the center</li>
		
	</ul>

</section>

<!--choose colour-->
<section id="comment">
<div class="choosecolor">
<h2 id="header">Choose your colour &nbsp</h2>
<div class="form-check">
  <input class="form-check-input" type="radio" name="new-color" id="new-color-red" value="red">
  <label class="form-check-label" for="new-color-red">Red</label>
</div>
<div class="form-check">
	<input class="form-check-input" type="radio" name="new-color" id="new-color-green" value="green">
	<label class="form-check-label" for="new-color-green">Green</label>
</div>
<div class="form-check">
	<input class="form-check-input" type="radio" name="new-color" id="new-color-yellow" value="yellow">
	<label class="form-check-label" for="new-color-yellow">Yellow</label>
  </div>
  <div class="form-check">
	<input class="form-check-input" type="radio" name="new-color" id="new-color-blue" value="blue">
	<label class="form-check-label" for="new-color-blue">Blue</label>
  </div>
</div>



<form name="commentform">
<div class="container">
	<div class="mb-3">
		<label for="new-email" class="form-label">Email address</label>
		<input type="email" class="form-control" id="new-email" placeholder="name@example.com">
	  </div>
	  <div class="mb-3">
		<label for="new-comment" class="form-label" placeholder="write your comments here">Comment</label>
		<textarea class="form-control" id="new-comment" rows="3"></textarea>
	  </div>
	  <button type="button"  onclick="processform()">Add comment</button>


	<div id="comments"class="box"> 
		<div id="c1001" class="d-flex">
			
		</div>
	</div>
		

</div>
</form>

</section>

<footer>
This website was updated on <time>2022-02-27</time>. <b>© Juhee Hur</b>
</footer>
</article>



</body></html>>

 

내가 만드려는 GGOOMING 랜딩페이지의 취지와 맞게 html 구조를 정리했다. 

<nav> 요소 밑에 <article> 을 쓸까 <section> 을 쓸까 고민하다가 <section>으로 나누고, 그 안에 필요하다면 <article> 을 쓰기로 했다. 

 

<article> 과 <seciton> 요소의 차이: 

https://diatomicc.tistory.com/71

 

HTML Article 과 Section의 차이

랜딩페이지를 제작하기 위해서 HTML 구조를 잡다가 문득 Article 과 Section중 무엇을 선택해야 할까 의문이 들었다. 두 태그 모두 HTML 5의 시맨틱 태그이다. 과 태그는 출력에 변경 사항이 없기 때문

diatomicc.tistory.com

 

 

2. 랜딩페이지 HTML구조 완성

 

<!DOCTYPE html>
<html>
	<head>
    <title>
        GGOOMING
    </title>
</head>

<body>

	<header>
	</header>

	<nav class="navbar" >
		<ul id="navigation">
			<li><a href="#about">About</a></li>
			<li><a href="#product">Product</a></li>
			<li><a href="#insight">Insight</a></li>
			<li><a href="#team">Team</a></li>
			<li><a href="#contact">Contact</a></li>
		</ul>
	</nav>


	<section id="about">
	</section>

	<section id="product">
	</section>

	<section id="insight">
	</section>

	<section id="team">
	</section>

	<section id="contact">
	</section>

	<footer>
	</footer>

</body>
</html>>
728x90
728x90

time 함수

time(), localtime()을 사용하기 위해선 <time.h>이라는 헤더파일을 추가해야한다.

 

time_t자료형은 unsigned int, unsigned long형으로 재정의 되어 있다

 

  1. time()함수로 얻어 온 값을 time_t형 변수에 저장한다
  2. 경과 시간을 지정할 영역을 지정하지만 보통은 NULL사용
  3. 그리니치 표준시로 1970년 1월 1일 자정부터 현재까지의 경과 시간을 초 단위로 계산한다
#include <stdio.h>
#include <time.h>

int main()
{
	time_t t;
	t = time(NULL);
	printf("1970년 1월 1일 자정부터 흘러온 시간 : %u초 \n", t);

	return;
}

1970년 1월 1일 자정부터 현재까지 흘러온 시간을 알 수 있다

 

local time 함수

localtime 함수로 얻어온 현재 시간 정보는 time.h에 미리 준비되어 있는 tm_구조체 변수에 저장된다

localtime함수에선 그 포인터만 반환함

#include <stdio.h>
#include <time.h>
#define _CRT_SECURE_NO_WARNINGS
#pragma warning(disable:4996)

int main()
{
	time_t t;
	struct tm* today;
	t = time(NULL);
	today = localtime(&t);

	int year, month, day;
	year = today->tm_year + 1900;
	month = today->tm_mon + 1;
	day = today->tm_mday;

	printf("오늘은 %d년 %d월 %d일 \n", year, month, day);
	printf("오늘은 %d일째 되는 날\n ", today->tm_yday);
	printf("현재시간 %d시 %d분 %d초 ", today->tm_hour, today->tm_min, today->tm_sec);
	 
	return;
}

 

난수 불러오기

srand()랑 rand()함수를 쓰기위해 stdlib.h 헤더파일 추가

 

- 정해진 난수표에서 순타적으로 수치를 가져온다

- 난수표는 os에 따라 수치의 순서가 다르게 짜여져 있다

- RAND_MAX 수피는 0~32767이다

 

#include <stdio.h>
#include <time.h>
#include <stdlib.h>


int main()
{
	printf("난수의 범위: 0부터 %d까지 \n", RAND_MAX);
	int num1 = rand();
	printf("숫자: %d\n", num1);

	//1에서부터 100사이의 난수 
	//컴퓨터가 제시하는 임의의수 나머지 연산 % 으로 처리
	//임의의 값 %6 => 나머지 계산후 +1
	int num2 = rand() % 100 + 1;
	printf("number:%d\n", num2);

	return;
}

이렇게 하면 RAND_MAX가 32767이기 때문에 0에서 부터 32767까지 숫자중 아무 숫자나 내보낸다. 

(컴터마다 고유의 난수가 있어서 바뀌진 않음)

num2는 %를 사용해서 1에서부터 100까지중 아무 수나 뽑아내라고 만들었는데 68이 나온걸 볼 수 있음.

 

그럼 아무 숫자나 5번 뽑아보자

#include <stdio.h>
#include <time.h>
#include <stdlib.h>


int main()
{
	int i;
	for (i = 0; i < 5; i++)
	{
		printf("random number: %d\n", rand());
	}
}

이렇게 for문을 써서 5개를 뽑으면 이렇게 랜덤한 수가 5개 나오긴 하는데 이 또한 컴터에 저장된 고유값이라 아무리 실행해도 똑같은 값이 계속 출력되는거임...

 

그래서 뭔가 유용하게 쓰려면 실행할때마다 값이 맨날 랜덤으로 바껴야 좋겠지? 

그래서 srand 를 쓰는거임

 

srand((int)time(NULL)); 이렇게 시간을 이용해서 렌덤으로 호출하게 만들거임. 

이때 시간을 seed(시드)값이라 하는데 이걸 심어서 난수를 만드는거임

#include <stdio.h>
#include <time.h>
#include <stdlib.h>

int rolldie();

int main()
{
	srand((int)time(NULL));

	int die1 = rolldie();
	int die2 = rolldie();

	printf("die : %d, %d", die1, die2);
	return; 

}

int rolldie()
{
	return rand() % 6 + 1;
}

이렇게 하면 매번 실행할때마다 1에서 6사이의 다른 값 두개가 출력됨 

 

이렇게

이거로 게임을 만들어볼거임

 

Up down game

#include <stdio.h>
#include <string.h>
#include <time.h>
#include <stdlib.h>

int random();

int main()
{
	srand((int)time(NULL));

	int num = random();//1에서 100까지의 렌덤한 숫자를 num에 저장
	int get = 0;
	int chance = 5;

	printf("what will be the number?:");

	while (chance > 0) {

		scanf_s("%d", &get);
		printf("chance left: %d\n", chance--);

		if (get > num) {
			printf("down\n");
		}
		else if (get < num) {
			printf("up\n");
		}
		else if (get = num) {
			printf("U got it!\n"); 
			break;
		}
		else
		{
			printf("error\n");
		}

		if (chance == 0)
		{
			printf("u use up all ur chances\n");
			break;
		}

		printf("try again:");

	}
	
}

int random()
{
	return rand() % 50 + 1;
}

2트클
5트클

1부터 50까지의 숫자 사이에 하나의 렌덤한 수를 num에 저장시킴.

num에 들어있는 숫자가 뭘까 맞추면 됨

이때 chance가 5번 주어지는데 이 chance안에 수를 맞춰야 함 

어떤 값을 넣으면 그 값이 num보다 작은지 큰지 if문을 써서 알려주는거임

728x90
728x90

대충 인수값이 없으면 void 있으면 int 씀 

 

#include <stdio.h>

/*void star() {
	printf("*************************\n");
	return;
}
void line() {
	printf("------------------\n");
}
*/
int addNum(int a, int b) {
	return a + b;
}

void star2(int type) {
	if (type == 1) {
		printf("*****************\n");
	}
	else if (type == 2) {
		printf("-----------------\n");
	}
	else {
		printf("그럼뭐임");
	}
}
 
int main() {
	printf("안녕하세요\n");

	for (int i = 0; i < 3; i++) {
		star2(1);
		star2(2);
	}
	int a;
	int b;
	int c;
	printf("함수\n");
	printf("숫자 2개 입력\n");
	printf("a=");
	scanf_s("%d", &a);
	printf("b=");
	scanf_s("%d", &b);

	c= addNum(a, b);
	printf("a+b= %d\n",c);
	star2(2);
}

 

 

 

대충 수를 받으면 돌려주는 코드

 

#include <stdio.h>

int star(int type) {
	printf("main에서 전달받은 값은 %d임\n", type);

	if (type >= 4) {
		printf("이거 안됨");
		exit(1);
	}
	else if (type == 1) {
		return type;
	}
	else if (type == 2) {
		return type;
	}
	else {
		printf("choose either 1 or 2");
		return type;
	}
}

int main() {

	int num;
	printf("type to print:");
	scanf_s("%d", &num);
	int c;
	c = star(num);
	printf("%d",c);
}

 

1. 숫자를 스켄해서 num에 넣음

2. star라는 함수에 들어감 키라키라도키도키

3. num이 4보다 같거나 크면 나가지고 1이면 1 돌려주고 2면 2돌려주고 3이면 1이나 2중에 고르라는 말을 내보낼거임

4. 결과가 c에 들어감

5. c를 프린트함

 

계산을 해주는 함수를 만들어보자

 

극한의 비효율 코드의 예시

나도 이거 쓰면서 처음 코드에서 조금 바꾼건데 그게 비효율적이였던거임

근데 이미 많이 써놔서 그걸 바꿀바에야 딴걸 바꾸겠다 해서 이래적었는데

코드상으로는 극한의 비효율인거임 나도 쓰면서 아차싶었음ㅋㅋ 위에서 다 프린트 하고 밑에선 호출만 하면 될것을..

나누기할때 double인 이유는 값이 float로 나와서 int쓰면 안나옴ㅋㅋ

 

#include <stdio.h>


int add(int a, int b) {
	return a + b;
}
int sub(int a, int b) {
	return a - b;
}
double div(double a, double b) {
	return a / b;
}
int mult(int a, int b) {
	return a * b;
}



int main() {

	int a,b,c,d,e;
	double f;

	printf("함수\n");
	printf("숫자 2개 입력\n");
	printf("a=");
	scanf_s("%d", &a);
	printf("b=");
	scanf_s("%d", &b);

	c = add(a, b);
	printf("a+b= %d\n", c);
	d = sub(a, b);
	printf("a-b= %d\n", d);
	e = mult(a, b);
	printf("a*b= %d\n", e);
	f = div(a, b);
	printf("a/b= %lf\n", f);


}

 

결과

 

조금은 더 효율적인..코드

 

#include <stdio.h>


int add(int a, int b) {
	printf("a+b= %d\n", a+b); 
	return;
}
int sub(int a, int b) {
	printf("a-b= %d\n", a-b);
	return;
}
double div(double a, double b) {
	printf("a/b= %fl\n", a/b);
	return;
}
int mult(int a, int b) {
	printf("a*b= %d\n", a*b);
	return;
}



int main() {

	int a, b;

	printf("함수\n");
	printf("숫자 2개 입력\n");
	printf("a=");
	scanf_s("%d", &a);
	printf("b=");
	scanf_s("%d", &b);

	add(a, b);
	sub(a, b);
	div(a, b);
	mult(a, b);



}

 

 

지역변수가 뭐냐 (local variable)

함수 내에만 존재하고 접근이 가능함

중괄호 내에 선언됨

지역 내에서만 유효함

해당 지역을 벗어나면 소멸됨

지역이 다르면 이름이 같아도 됨

 

전역변수가 뭐냐 (global variable)

전역한 변수임

중괄호 내에 선언안됨

프로그램 어디서든 접근가능

종료할때까지 존재

초기화 안하면 0값

전역이랑 지역이랑 겹치면 지역이 먼저임

 

정적 지역 변수가 뭐냐 (static local variable)

static 이 붙어있으면 값이 고정되어서 사용됨

선언됨 함수 내에서만 접근가능

 

#include <stdio.h>

int a, b;//전역변수

int main() {
	
	printf("입력:");
	scanf_s("%d%d", &a, &b);
	printf("결과 %d",add(a,b));
}

int add() {
	static int a = 10;
	return a + b;
}

a값을 입력 받아도 이미 10이 정적지역변수에 들어가있어서 계산은 10으로됨. 

즉 20이랑 5가 스켄되더라도 10이랑 5로 계산되는거임

 

초를 시간으로 바꾸는걸 짜보자

#include <stdio.h>

const int H = 60 * 60;
const int M = 60;

void StoHMS(int sec);

int main(void) {
	int sec;

	printf("초:");
	scanf_s("%d", &sec);
	StoHMS(sec);

	return 0;
}

void StoHMS(int sec) {
	int h, m, s;

	h = sec / H;
	sec = sec % H;

	m = sec / M;
	sec = sec % M;

	s = sec;
	printf("[%d 시간],[%d 분],[%d 초]\n", h, m, s);
}

 

const int 는 선언할때 말고는 값을 더 못넣어서 특정한 값 하나를 지정해서 계속 쓰고 싶을때 쓰면 되는거임. 

 

자 일단 1시간은 1초의 60*60배니까 저렇게 선언해놓고

M는 1초의 60배니까 저래 해 놨음

 

메인함수에는 함수만 호출하도록 할거임. 

자 그럼 Second 를 M이랑 H로 바꾸는 함수를 만들어보자. 일단 sec를 H로 나누면 몇시간이 나오는지 보여주겠지?

그리고 남는 s값(나머지)를 sec에 다시 넣는거임. 이제 그 나머지로는 더이상 H가 안나오니까

나누기 M(60)해서 몇분인지를 구하는거임

그리고 또 남는값을 구해서 분으로도 못만드는 나머지들을 구해서 그걸 sec에 넣고 출력하면 되는거야 (사실 그래보면 s라는 변수선언 안해도 되긴 해 그냥 sec 프린트 하면 되지)

 

그래서 나온 값을 프린트하면 몇시간 몇분 몇초인지 나온답니다-

 

#include <stdio.h>

const int H = 60 * 60;
const int M = 60;

void StoHMS(int sec);

int main(void) {
	int sec;

	printf("초:");
	scanf_s("%d", &sec);
	StoHMS(sec);

	return 0;
}

void StoHMS(int sec) {
	int h, m;

	h = sec / H;
	sec = sec % H;

	m = sec / M;
	sec = sec % M;

	printf("[%d 시간],[%d 분],[%d 초]\n", h, m, sec);
}

극한의 효율충...?

사실 저거 함수 배울려고 하는거라 코드 자체가 비효율적임 아ㅋㅋ

728x90

+ Recent posts