Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Program in c++ tell if a number is integer or float

Tags:

c++

I used function overload to check if an input number is integer or float. However I get this following error: error: call of overloaded 'retNr(double)' is ambiguous|

#include <iostream>
using namespace std;

void retNr(int x)
{
    cout << "The entered number is an integer. " << endl;
}

void retNr(float x)
{
    cout << "The entered number is a float. " << endl;
}

int main()
{
    cout << "Please enter a number: " << endl;
    cin >> nr;
    retNr(nr);
    return 0;
}
like image 343
Cantaff0rd Avatar asked Mar 20 '23 01:03

Cantaff0rd


2 Answers

Read from cin into a string and then check the string for the presence of a decimal point. If there is a decimal point, call atof() on the string to convert it to a float, otherwise call atoi() to convert it to an integer.

like image 68
Logicrat Avatar answered Apr 01 '23 22:04

Logicrat


Make some small change in:

void retNr(double x)
{
    cout << "The entered number is a double. " << endl;
}

Remember to declare your nr variable.

double d = 1.0;
int i = 1;

retNr(d);
retNr(i);
like image 42
Dakorn Avatar answered Apr 01 '23 23:04

Dakorn