기록하고 까먹지 말기

과제 2 - Operator & Binary(1 ~ 5) 본문

전공/C

과제 2 - Operator & Binary(1 ~ 5)

yha97 2021. 6. 21. 14:05

기본적인 operator와 binary operator의 개념을 묻는 과제였다.

 

과제를 진행하면서 주로 xor를 통한 swap과 unsigned, signed integer type이 헷갈렸기 때문에 중간중간 구글의 도움을 받아 해결했다.

 

또한 2진수와 16진수 문제를 풀면서 2학년에 배웠던 컴퓨터구조의 opcode 연산도 생각났다.

 

3자리의 정수를 입력받은 후 각 자릿수를 출력하는 프로그램이다.

 

각 자리수를 저장하여 출력하는 방식과 출력과 동시에 연산하는 방법이 있다.

 

그 중에서 나는 연산과 동시에 출력하는 방식으로 과제를 해결했다.

#include <stdio.h>

int main(){
	int n;
	
	printf("Enter 3-digit number : "); // Enter a 3 digit number
	scanf("%d", &n);
	
	// printing results with calculating
	printf("1st digit :%d\n", n/100);
	printf("2nd digit :%d\n", n/10%10);
	printf("3rd digit :%d\n", n%10);
	return 0;
}

각 자릿수를 구할 때 div와 mod를 잘 사용하면 될 것이다.

 

 

중학교때 배운 연립방정식을 푸는 문제이다. 너무 어렵게(?) 생각하지 말고 한쪽으로 이항하여 문제를 푸는 방식을 사용하면 될 것이다.

 

다만, 값이 소수점이 나오는 경우가 있기 때문에 type은 위에 제시간 대로 int를 float로 변환하는 casting을 이용하면 될 것이다.

 

#include <stdio.h>
 
int main(){
	int a, b, c; 
	int d, e, f;
	double var1, var2;
	
	printf("input coefficient a,b,c:");
	scanf("%d, %d, %d",&a,&b,&c); // get a value of the a, b, c
	printf("input coefficient d,e,f:");
	scanf("%d, %d, %d",&d,&e,&f); // get a value of the d, e, f
	
	printf("%The two linear equations are: \n");
	printf("%dx+%dy+%d \n",a,b,c);
	printf("%dx+%dy+%d \n",d,e,f);
	
	var1 = (c*e-b*f)/(b*d-a*e); //calculating the value of the var1
	var2 = (a*var1+c)/(-b);	//calculating the value of the var2
	
	printf("Intersection point is <%.2f,%.2f>",var1,var2); //print the value of var1, 2
	return 0;
}

 

이 문제의 경우 엄청 깔끔한 문제는 아닌지라 ax+by+c = 0, dx+ey+f = 0으로 값을 치환하여 수기로 문제를 풀고 이를 코드에 옮겨적는 방식으로 진행했다.

 

16진수인 두 수를 가지고 위의 아웃풋을 operator를 통해 출력하는 문제이다.

 

맨 처음 문제와 힌트를 보지 않고 단순히 어떻게 해야 하나 한동한 막막했는데 문득 힌트를 보고 나서 슈슈슉 풀었던 것 같다.

 

#include <stdio.h>

int main(){
	int a = 0xAF; // declare 0xAF and 0xB5
	int b = 0xB5;
	
	// printing results
	printf("%x\n", (a&b)); // a and b
	printf("%x\n", (a|b)); // a or b
	printf("%x\n", (a^b)); // a xor b
	printf("%x\n", (~a)); // a in bitwise complement 
	printf("%x\n", (a<<2)); // shifting left 2 bits with a
	printf("%x\n", ((a>>1)&(b>>3))); // and operating between shift 1 bits with a and shift 3 bits with a
	
	return 0;
}

문제를 풀면서 and, or, not은 종종 사용하여 익숙했지만 xor와 bitwise연산자들은 컴퓨터 구조 이후에 그닥 사용하지 않아 처음에는 어색했다.

 

또힌 16진수를 출력하는 %x 연산자 또한 이 과제를 통해 처음 사용하는지라 약간의 적응이 필요했다.

 

이번 과제에서 가장 의미있는 문제가 아니었나 싶다.

 

10진수를 2진수로 변환 및 invert를 했을 때의 10진수의 값을 출력하는 문제이다.

 

2의 보수가 왜 있어야 하는지를 보여주는 과제이다.

 

#include <stdio.h>

int main(){
	int n; // declare integer number
	
	// input a number
	printf("Enter any number: ");
	scanf("%d", &n);
	
	printf("Original number = %d (int decimal)\n", n); // printing original number
	printf("Number after bits are flipped = %d (in decimal)\n", ~n); // printing flipped number with operator
	return 0;
}

 

 

두 수를 입력받고 bitwise operator를 통해 swap하는 문제이다.

 

이 문제가 해당 과제에서  가장 애먹게 했었던 것 같다. 평소 temp를 선언하여 swap하는 나였지만 이런 방법이 있을줄은 몰랐기 때문에 기억에 남는다.

 

#include <stdio.h>

int main(){
	int n1, n2;
	
	// input 2 numbers n1, n2
	printf("Enter any two number: ");
	scanf("%d, %d", &n1, &n2);
	
	// printing values of inputed numbers
	printf("Original value of num1 = %d\n", n1);
	printf("Original value of num2 = %d\n", n2);
	
	// swapping with bitwise operator
	// ^ 연산자 : XOR 
	n1 ^= n2;
	n2 ^= n1;
	n1 ^= n2;
    
    // printing results
    printf("Num1 after swapping = %d\n", n1);
    printf("Num2 after swapping = %d\n", n2);
    return 0;
}

이걸 하면서 느끼는게.... 역시 temp로 하는게 난 더 편한거같다...ㅎㅎ

 

괄호를 넣음으로써 연산의 순서를 파악하라는 문제이다.

 

아래 표를 확인하면 더 쉬울 것이다.

 

출처 : http://kjlife.egloos.com/m/2329290

#include <stdio.h>

int main(){
	int a = 10, b = 5;
	int num;
	
	num = ((a / b) * 2); // first : division, second : multiplication
	printf("num= %d\n", num); // printing result
	
	num = ((++a) * 3); // first : pre-increment, second : multiplication
	printf("num= %d\n", num);// printing result
	
	// first: comparing a and b, second : estimating whether a is not 5, third : operating first and second
	num = ((a > b) && (a != 5)); 
	printf("num= %d\n", num);// printing result
	
	num = ((a % 3) == 0); // first: reninding a with 3, second : estimating value of first is 0
	printf("num= %d\n", num);// printing result
	
	return 0;
}

이 문제도 기존 수학지식을 갖고 있다면 큰 어려움은 없을 것이라고 생각한다.

 

3개의 점수로 대표되는 정수를 입력받은 후 해당 점수들의 합, 평균, 퍼센트를 출력하는 프로그램이다.

 

total, average, percentage는 소수점이 포함된 채로 출력해야 하기 때문에 double형으로 선언하여 문제를 해결하였다.

 

#include <stdio.h>

int main(){
	int n1, n2, n3;
	double total;
	double avg;
	double per;
	
	// input three scores
	printf("Enter score of three subjects: \n");
	scanf("%d %d %d", &n1, &n2, &n3);
	
	// calculating total, average, percentage
	total = n1+n2+n3;
	avg = total / 3;
	per = (total / 300) * 100;
	
	// print all results
	printf("Total = %.2f\n", total);
	printf("Average = %.2f\n", avg);
	printf("Percentage = %.2f\n", per);
	return 0;
}

퍼센테이지의 개념을 확실하게 알 수 없었기 때문에 이 또한 구글링을 통해 문제를 해결했다.

 

예전에 수학공부좀 열심히 할 걸 그랬다.

 

* 퍼센트(%) = 평균 * 100

'전공 > C' 카테고리의 다른 글

과제 4 - Control Flow (6 ~ 9)  (0) 2021.06.21
과제 4 - Control Flow (1 ~ 5)  (0) 2021.06.21
과제 3 - Data types (1 ~ 7)  (0) 2021.06.21
과제 1 - variable (6 ~ 9) (범위포함 x)  (0) 2021.06.21
과제 1 - variable (1 ~ 5)  (0) 2021.06.21