Home > OS >  takes one float value and immediately ends the program in template c
takes one float value and immediately ends the program in template c

Time:10-20

okay so I have a question where im required to take user input of two int or float and then find the maximum and minimum of those two numbers. my if loop for int works fine, but for the float , it takes one float value and immediately ends the program. can anyone help me with this error? here's my code:

     #include <iostream>
     using namespace std;
     template <class T>
     class mypair
     {
       T a;
       T b;
public:
mypair(T a=0, T b=0)
{
    this->a=a;
    this->b=b;
}
void setFirst(T a)
{
    this->a = a;
}
T getFirst()
{
    return a;
}

void setSecond(T b)

{
    this->b = b;
}
T getSecond()
{
    return b;
}
T getmax();
T getmin();
};
template <class T>
T mypair<T>::getmax()
{
T retval;
retval = getFirst() > getSecond() ? getFirst() : getSecond();
return retval;
}
template <class T>
T mypair<T>::getmin()
{
T min;
min = getFirst() < getSecond() ? getFirst() : getSecond();
return min;
}
int main()
{
char opt;
cout << "program to find a minimum and maximum" << endl;
cout << "--------------------------------------------" << endl;
cout << "Do you want to type in two integers or two floats ?"<<endl;
cout << "(i for integer , f for float)"<<endl;
cin >> opt;

if (opt == 'i' || opt == 'I')
{
    mypair<int>  myobject;
    int int1, int2;
    cout << "Enter first INT = ";
    cin >> int1;
    myobject.setFirst(int1);
    cout << "Enter second INT = ";
    cin >> int2;
    myobject.setSecond(int2);
    cout << "---------------------------------------" << endl;
    int choice;
    cout << "Find Maximum or Minimum?" << endl;
    cout << "(1 for maximum ,0 for minimum)" << endl;
    cin >> choice;
    if (choice == 0)
    {
        cout << myobject.getmin();
    }
    if (choice == 1)
    {
    
        cout << myobject.getmax();
    }
}
if (opt == 'f' || opt == 'F')
{
    mypair <float> myobject1;
    int fl1, fl2;
    cout << "Enter first FlOAT = ";
    cin >> fl1;
    myobject1.setFirst(fl1);
    cout << "Enter second FLOAT = ";
    cin >> fl2;
    myobject1.setSecond(fl2);
    cout << "---------------------------------------" << endl;
    int choice;
    cout << "Find Maximum or Minimum?" << endl;
    cout << "(1 for maximum ,0 for minimum)" << endl;
    cin >> choice;
    if (choice == 0)
    {
        cout << myobject1.getmin();
    }
    if (choice == 1)
    {
        cout << myobject1.getmax();
    }
}


return 0;
}

CodePudding user response:

In if (opt == 'f' || opt == 'F') you declared numbers as int, not as float.

  • Related