Menu
CoddyTech

부동소수점 연산

Coddy의 C++ 개발자를 위한 C 코스 레슨. 48개 중 5번째.

두 언어 모두 정수 나눗셈 전에 변환해야 합니다. C는 static_cast 대신 캐스트 구문을 사용하고, iostream 조작자 대신 printf 정밀도를 사용합니다. 서식 지정 API를 바꾸더라도 사라진 소수 부분은 복원되지 않습니다.

실수 결과를 얻으려면 나눗셈 전에 피연산자를 변환하세요. 이미 절삭된 몫을 변환해도 소수 부분을 복구할 수 없습니다.

C++ 예제

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <memory>
#include <algorithm>
#include <functional>
#include <variant>
#include <sstream>

int main(){
std::cout << std::fixed << std::setprecision(2) << static_cast<double>(5)/2 << "\n";
}

C++ 출력:

2.50

C 예제

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>

int main(void) {
printf("%.2f\n",(double)5/2);
return 0;
}

C 출력:

2.50
challenge icon

챌린지

쉬움

입력은 두 정수 a와 0이 아닌 b입니다. 두 수의 분수 비율을 double로 반환하세요. 드라이버는 소수점 아래 두 자리까지 출력합니다.

잠금 해제된 소스 파일과 헤더 파일을 수정하세요. 표시된 잠금 상태의 main.c가 함수를 직접 호출하므로 선언된 공개 API와 호환되도록 유지하세요. 다른 main을 추가하지 마세요. 작업에서 특정 범위를 확인한다고 명시하지 않는 한 모든 숫자 작업 테스트 데이터는 오버플로가 발생하지 않을 만큼 작습니다. 지정된 출력만 출력하세요. 입력 파싱과 출력이 표시된 경우 드라이버가 이를 처리합니다.

직접 해보기

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){int a,b;if(scanf("%d%d",&a,&b)!=2)return 1;printf("%.2f\n",ratio(a,b));return 0;}
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

C++ 개발자를 위한 C의 모든 레슨

직접 연습해 보세요: 온라인 C 컴파일러