@yii_lover

Как правильно сравнить два числа double и число приведенное к double?

У меня такая проблема. Два числа одинаковых на вид C++ считает не одинаковыми. Одно число у меня по умолчанию double, другое сначала приводится к int, потом к double (для того, чтобы увидеть только целую часть)

Код всей программы
#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


По ссылке можно это потыкать.
cpp.sh/6iurs
  • Вопрос задан
  • 1214 просмотров
Решения вопроса 1
GavriKos
@GavriKos
Вычесть одно из другого, взять от этого модуль и проверить меньше ли результат константной точности. Если меньше - числа равны (с точностью до...)
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы