C/연습장
0309 <if 조건문>
joo_coding
2025. 3. 9. 20:26
// 사칙연산
int opt;
double num1, num2;
double result;
printf("1.덧셈 2.뺄셈 3.곱셈 4.나눗셈 \n");
printf("몇번을 실행할까요?: ");
scanf("%d", &opt);
printf("2개의 실수 입력:");
scanf("%lf %lf", &num1, &num2);
if(opt==1)
result = num1 + num2;
if(opt==2)
result = num1 - num2;
if (opt==3)
result = num1 * num2;
if (opt==4)
result = num1 / num2;
printf("결과: %f \n", result);
// p.189
// 문제1
// 1~100 중에서 7의 배수와 9의 배수를 출력
// 단, 7의 배수이면서 9의 배수인 경우 한번만 출력
int num;
for (num = 1; num < 101; num++)
{
/* code */
if (num%7==0 || num%9==0)
{
printf("%d \n", num);
}
}
// 문제2
// 2개의 정수를 입력받아, 차를 출력
// 무조건 큰수에서 작은수를 빼야함
// 출력결과는 무조건 0 이상
int num1,num2;
printf("정수 2개를 입력하세요.");
scanf("%d %d", &num1, &num2);
int result = 0;
if (num1>num2)
result = num1 - num2;
else
result = num2 - num1;
printf("결과: %d", result);
int kor, eng, math;
printf("국,영,수 점수를 차례로 입력하세요.:");
scanf("%d %d %d", &kor, &eng, &math);
// double total;
// total = (kor+eng+math)/3;
// printf("평균: %lf점 \n", total);
int total;
total = (kor+eng+math)/3;
printf("평균: %d점 \n", total);
if (total>=90)
printf("A \n");
else if (total>=80)
printf("B \n");
else if (total>=70)
printf("C \n");
else if (total>=60)
printf("D \n");
else
printf("F \n");
return 0;
평균 계산할 때, 실수로 해도되고 정수로 해도되고
<조건 연산자>
조건식 ? 참일_경우_값 : 거짓일_경우_값;
ex)
#include <stdio.h>
int main() {
int a = 10, b = 5;
// a가 b보다 크면 "a가 크다" 출력, 아니면 "b가 크다" 출력
a > b ? printf("a가 크다\n") : printf("b가 크다\n");
return 0;
}
// 문제4
// 문제2를 조건연산자 사용하여 풀기
int num1,num2;
printf("정수 2개를 입력하세요.");
scanf("%d %d", &num1, &num2);
num1 > num2 ? printf("%d",num1-num2):printf("%d",num2-num1);
return 0;