Answer the question
In order to leave comments, you need to log in
How to correctly compare two double numbers and the number reduced to double?
I have such a problem. C++ considers two numbers that look the same to be not the same. I have one number by default double, the other is first converted to int, then to double (in order to see only the integer part)
Code of the whole program
#include <iostream>
#include <cstdlib>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iomanip>
#include <math.h>
#include <typeinfo>
using namespace std;
int main()
{
const size_t BUFFER_SIZE = 1024;
char sym[BUFFER_SIZE]; //ИСПОЛЬЗУЮ КАК БУФЕР
char fractBuf[BUFFER_SIZE]; //ИСПОЛЬЗУЮ КАК БУФЕР
char * pEnd;
// char * pEnd;
int basNotation; // система счисления
long int tempNumberInt;// конечное число
long int tempNumberFract;// конечное число
//long int resultNumber;// конечное число
//cout<<num;
double int_part, fract_part;
int power = 0;
cout << "Input a number: ";
cin >> sym;
cout << endl;
double num = strtod(sym,&pEnd);
fract_part = modf(num, &int_part);
cout<<"int: "<<int_part<<endl;
cout<<"fract: "<<fract_part<<endl;
cout<<" type: "<<typeid(fract_part).name()<<endl;
while ( fract_part != ( (double)( (int)(fract_part + 0.5) ) ) ) {
fract_part *= 10;
power++;
cout<<fract_part<<"/"<<((double)((int)(fract_part + 0.5)))<<endl;
cout<<"res:"<<( (double)( (int)(fract_part + 0.5) ) )<<endl;
cout<<" type: "<<typeid(fract_part).name()<<endl;
if(power==2){
return 0;
}
} ;
//sprintf (fractBuf, "%f", fract_part);
cout<<int_part<<" - "<<(int)fract_part<<endl;
cout << "Input a scale of notation (only binary-2,octagonal-8,decimal-10,hexadecimal-16): ";
do
{
cin >> basNotation;
}
while (basNotation!=2 && basNotation!=8 && basNotation!=10 && basNotation!=16);
//sprintf (sym, "%f", fract_part)
tempNumberInt = strtol(sym, &pEnd, basNotation);
tempNumberFract = strtol(fractBuf, &pEnd, basNotation);
cout << fixed << left << tempNumberInt << right << tempNumberFract;
}
Input a number: 11.11
// Первая итерация
int: 11
fract: 0.11
type: d
// Вторая итерация
1.1/1
res:0
type: d
11/11
res:0
type: d
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question