Last active
April 18, 2020 09:44
-
-
Save fpdjsns/83c1b2d3f157f68a1c7687948477b400 to your computer and use it in GitHub Desktop.
실수 출력(정수 부분, 반올림, 올림, 내림)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
using namespace std; | |
int main() | |
{ | |
float ans, temp; | |
ans = 4.7777; | |
temp = ans; | |
printf("원래 수 : %f\n", ans); | |
//정수부분 출력 | |
printf("정수부분 : %d\n", (int)temp); | |
//소수점 넷 째 자리 반올림 | |
printf("반올림 : %0.3f\n", temp); | |
temp = temp + 0.0005; | |
temp = (int)(temp * 1000); | |
temp = temp / 1000; | |
printf("반올림2 : %f\n", temp); | |
temp = ans; | |
//소수점 넷 째 자리 올림 | |
temp = temp + 0.0009; | |
temp = (int)(temp * 1000); | |
temp = temp / 1000; | |
printf("올림 : %f\n", temp); | |
temp = ans; | |
temp = temp * 1000; | |
temp = ceil(temp);//소수점 올림 | |
temp = temp / 1000; | |
printf("올림2 : %f\n", temp); | |
temp = ans; | |
//소수점 넷 째 자리 버리기 | |
temp = (int)(temp * 1000); | |
temp = temp / 1000; | |
printf("내림 : %f\n", temp); | |
temp = ans; | |
temp = temp * 1000; | |
temp = floor(temp); //소수점 이하 버림 | |
temp = temp / 1000; | |
printf("내림2 : %f\n", temp); | |
return 0; | |
} |
근데 실수를 scanf를 통해 입력받는 경우이면 어떻게 되나요?
@neonin04 달라지는건 크게 없습니다.
8번째 줄 대신scanf("%f", &ans);정도로만 해주면 될 것 같네요.
전 이렇게 구현했는데 혹시 왜 안되는지 봐주실 수 있나요?ㅠㅠㅠ
강제 형변환을 쓰려고 한겁니다ㅠㅠ
int main() {
double a;
printf("999이하의 실수를 입력하세요:");
scanf("%lf", &a);
printf("a = %lf\n\n", a);
printf("a(반올림) = %.3lf\n", (double)((int)(a * 1000 + 0.5)) / 1000);
printf("a(내림) = %.3lf\n", (double)((int)(a * 1000)/1000));
printf("a(올림) = %.3lf\n\n", (double)((int)(a * 1000 + 0.9)) / 1000);
return 0;
}
@neonin04 음.. 저 코드가 어떤 결과가 나오는지는 모르겠지만 코드만 보고 추측해보건데, 자료형 문제인 것 같네요.
(int)(a*1000) 는 int 형입니다. 1000도 int 형입니다. int / int = int 가 될 것이고 int 형은 실수형이 아니여서 소수점 아래에 대한 정보를 다 잃어버립니다.
이미 소수점 정보를 잃어버린 정수형을 이후에 실수형으로 만들어봤자 소수점에 대한 정보를 제대로 인식할 수 없겠군요.
printf할 때 double형을 출력하겠다고 했는데 실제로 변수타입은 int 형이여서 여기서 전환될 때 타입 불일치로 그럴수도 있구요. (아닐수도 있습니다. 모든건 추측 ^^)
그래서.. 결론은 계산을 할 때 int형인 아닌 double형으로 타입 변환이 필요합니다. 분자는 형변환해서 소수점을 날려줘야 해서 int형으로 가야한다고 한다면 분모를 double형으로 하면 됩니다.
printf("a = %lf\n\n", a);
printf("a(반올림) = %.3lf\n", ((int)(a * 1000 + 0.5)) / (double)1000);
printf("a(내림) = %.3lf\n", ((int)(a * 1000)/(doble)1000));
printf("a(올림) = %.3lf\n\n", ((int)(a * 1000 + 0.9)) / (double)1000);
ㅠㅠ너무너무 감사합니다!!! 몇 시간 뒤져서 공부해도 명확한 답은 안나왔는데ㅠㅠㅠㅠ
해결 됐습니다!!!!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
thanks