전공/C
과제 4 - Control Flow (6 ~ 9)
yha97
2021. 6. 21. 15:24

입력받은 점수들의 퍼센트를 구하고 if, else문을 통해 해당 점수들의 등급을 매기는 문제이다.
for문을 통해 5개의 점수를 입력받고 평균및 퍼센트를 구한 후 case에 따라 grade를 출력하면 된다.
#include <stdio.h>
int main(){
int n1, n2, n3, n4, n5;
char g;
printf("Enter five subjects marks: ");
scanf("%d %d %d %d %d", &n1, &n2, &n3, &n4, &n5); // inputs 5 marks
float total = (float)(n1+n2+n3+n4+n5)/5; // calculating total percentages
printf("Percentage = %.2f\n", total);
// getting grade by total
if(total >= 90)
g = 'A';
else if(total >= 80)
g = 'B';
else if(total >= 70)
g = 'C';
else if(total >= 60)
g = 'D';
else if(total >= 50)
g = 'E';
else
g = 'F';
//prints outputs
printf("Grade %c", g);
return 0;
}
평균(퍼센트)를 구하는 경우 소수점이 나올 수 있기 때문에 float를 사용하였고 int를 float로 변환하도록 casting을 활용했다.

Q6를 switch문으로 구현하는 문제다.
#include <stdio.h>
int main(){
int n1, n2, n3, n4, n5;
char g;
printf("Enter five subjects marks: ");
scanf("%d %d %d %d %d", &n1, &n2, &n3, &n4, &n5); // inputs 5 marks
int total = (n1+n2+n3+n4+n5)/5; // calculating total percentages
printf("Percentage = %d\n", total);
total = total / 10; // calculting total to operate switch
// getting grade by total
switch(total){
case 9:
g = 'A';
break;
case 8:
g = 'B';
break;
case 7:
g = 'C';
break;
case 6:
g = 'D';
break;
case 5:
g = 'E';
break;
default:
g = 'F';
break;
}
//prints outputs
printf("Grade %c", g);
return 0;
}

3개의 각도를 입력받고 이를 통해 삼각형을 이룰 수 있는지의 여부를 묻는 문제이다.
삼각형의 세 각의 합은 무조건 180도가 된다는 개념을 알아야 해결 가능하다.
#include <stdio.h>
int main(){
int n1, n2, n3;
printf("Enter three angles of triangle:\n"); // input three numbers
scanf("%d %d %d", &n1, &n2, &n3);
if((n1+n2+n3) == 180) // check whether total angle is same with triangle
printf("Triangle is valid."); // print output
else
printf("Triangle is not valid.");
return 0;
}

switch문을 통해 두 수와 operator를 입력받고 그에 따른 결과값을 출력하는 프로그램이다.
operator를 char형으로 받고 그에 따라 switch문을 통해 연산 방식을 설정하는 것이 관건인 문제이다.
#include <stdio.h>
int main(){
int n1, n2;
char cal;
// intro
printf("SIMPLE CALCULATOR\n");
printf("Enter [number 1] [+ - * /] [number 2]\n");
scanf("%d %c %d", &n1, &cal, &n2); // input number and character from user
//print the output based on the switch
switch(cal){
case '+':
printf("%.2f + %.2f = %.2f", (float)n1, (float)n2, (float)(n1+n2));
break;
case '-':
printf("%.2f + %.2f = %.2f", (float)n1,(float)n2, (float)(n1-n2));
break;
case '*':
printf("%.2f + %.2f = %.2f", (float)n1, (float)n2, (float)(n1*n2));
break;
case '/':
printf("%.2f + %.2f = %.2f", (float)n1, (float)n2, (float)(n1/n2));
break;
}
return 0;
}
operator별 case를 잘 설정하고 int형으로 받은 숫자를 float형으로 출력하기 위해 casting을 활용하였다.