만들면서 배우는 C언어 > Chapter9 포인터)
: Programming 5번 문제를 풀다가 근의 공식, double에 관하여 좀 더 보완할 부분
1차로 작성한 코드
#include <stdio.h>
#include <math.h>
void quadratic(int a, int b, int c, double* xplus, double* xminus);
int main() {
double xplus, xminus;
int a = 1, b = 4, c = 3;
quadratic(a, b, c, &xplus, &xminus); // a = 1, b = 4, c = 3
printf("첫 번째 실근: %lf\n", xplus);
printf("두 번째 실근: %lf\n", xminus);
return 0;
}
void quadratic(int a, int b, int c, double* xplus, double* xminus) {
*xminus = (-b - sqrt (b*b - 4*a*c)) / (2*a);
*xplus = (-b + sqrt(b * b - 4 * a * c)) / (2 * a);
}
보완할 점
Check if roots are real (not NaN (Not a Number))
NaN 사용을 위한 라이브러리
c : <math.h>
c++ : <cmath>
2차로 작성한 코드 (C)
#include <stdio.h>
#include <math.h>
void quadratic(int a, int b, int c, double* xplus, double* xminus);
int main() {
double xplus, xminus;
int a = 1, b = 4, c = 3;
quadratic(a, b, c, &xplus, &xminus); // a = 1, b = 4, c = 3
// NaN인지 Check
if (!isnan(xplus) && !isnan(xminus)) {
printf("첫 번째 실근: %lf\n", xplus);
printf("두 번째 실근: %lf\n", xminus);
}
return 0;
}
void quadratic(int a, int b, int c, double* xplus, double* xminus) {
double discriminant = b * b - 4 * a * c;
if (discriminant >= 0) {
*xminus = (-b - sqrt(discriminant)) / (2 * a);
*xplus = (-b + sqrt(discriminant)) / (2 * a);
}
else {
*xminus = *xplus = NAN; // C
}
}
2차로 작성한 코드 (C++)
#include <iostream>
#include <cmath>
void quadratic(int a, int b, int c, double* xplus, double* xminus);
int main() {
double xplus, xminus;
int a = 1, b = 4, c = 3;
quadratic(a, b, c, &xplus, &xminus); // a = 1, b = 4, c = 3
// NaN인지 Check
if (!std::isnan(xplus) && !std::isnan(xminus)) {
std::cout << "첫 번째 실근: " << xplus << '\n';
std::cout << "두 번째 실근: " << xminus << '\n';
}
return 0;
}
void quadratic(int a, int b, int c, double* xplus, double* xminus) {
double discriminant = b * b - 4 * a * c;
if (discriminant >= 0) {
*xminus = (-b - std::sqrt(discriminant)) / (2 * a);
*xplus = (-b + std::sqrt(discriminant)) / (2 * a);
}
else {
*xminus = *xplus = std::nan(""); // C++
}
}
시스템 프로그래밍 시간에 배웠던 부동 소숫점을 이용하는 double에 관하여 배운 것이 생각났다.
'math 라이브러리'에 있는 'isnan' 함수로 NaN인지 확인할 수 있다.
만들면서 배우는 C언어 | 생능출판사
C언어는 현재에도 1, 2위를 다투는 중요하고 인기 있는 언어이다. C언어를 통하여 학습자들은 컴퓨터의 작동 방식에 대하여 깊이 이해하게 될 것이다. 이 책은 C 프로그래밍에 대한 체계적인 학습
www.booksr.co.kr
'C&C++' 카테고리의 다른 글
| C++ getline() 종류 (0) | 2024.10.20 |
|---|---|
| Hackerrank > C++ > Classes > Box it! (0) | 2024.03.08 |