C ++使用函数模板查找任何输入数据类型的中间值?

时间:2015-03-11 00:40:50

标签: c++ function templates

我遇到了一些问题,起初看起来很简单,但现在我似乎无法解决这个问题,任何帮助都会非常感激。

所以问题是:用户输入三个数据类型的值,int,float或char。然后程序必须返回中间值。

这是我到目前为止所拥有的:

练习要求我使用函数模板而不是数组。

标题文件:

#ifndef MIDTEMP_H
#define MIDTEMP_H

template <class T>
T doMiddle(T param, T param2, T param3)
{
   if ((param<param2 && param>param3) || (param<param3 && param>param2) || (param == param2 == param3))
    {
       return param;
    }
   else if ((param2<param && param2>param3) || (param2<param3 && param2>param) || (param2 == param == param3))
    {
      return param2;
    }
   else if ((param3<param2 && param3>param) || (param3<param && param3>param2) || (param3 == param2 == param))
    {
      return param3;
    }
   else if (param == param2 && param < param3)
    {
      return param;
    }

}

#endif

现在是测试我的标题函数的代码:

#include<iostream>
#include "Middle.h"
using std::cin;
using std::cout;
using std::endl;

int main()
{
cout << "Please enter 3 integers. IF input is incorrect please input until correct." << endl;
cout << endl;
int a, b, c;
while (!(cin >> a >> b >> c))
{
    cin.clear();
    cin.ignore();
}
cout << "The Middle is: " << doMiddle(a, b, c) << endl;
cout << endl;

//=======================================================

cout << "Please enter 3 floating point values.  IF input is incorrect please input until correct." << endl;
cout << endl;
float d, e, f;
while (!(cin >> d >> e >> f))
{
    cin.clear();
    cin.ignore();
}
cout << "The Middle is: " << doMiddle(d, e, f) << endl;
cout << endl;

//=======================================================

cout << "Please enter 3 characters. IF input is incorrect please input until correct." << endl;
cout << endl;
char g, h, j;
while (!(cin >> g >> h >> j))
{
    cin.clear();
    cin.ignore();
}
cout << "The Middle is: " << doMiddle(g, h, j) << endl;
cout<<endl;
return 0;
}

所以它运作得体,但我可以说我这样做(来自cmd):

请输入3个整数。如果输入错误,请输入直到正确。

5 3.2 6 2 中间是:2

请输入3个浮点值。 IF输入不正确请输入

9.0 9 9 中间是:-1。#IND

请输入3个字符。如果输入错误,请输入直到正确。

ř [R [R 中间是:r

为什么它返回-1。#IND值并且有没有其他方法可以做到这一点而没有那些荒谬的if语句?

2 个答案:

答案 0 :(得分:1)

template<class T>
T doMiddle(T t1, T t2, T t3){
  T arr[]={t1,t2,t3};
  using std::begin; using std::end;
  std::nth_element( begin(arr), begin(arr)+1, end(arr) );
  return arr[1];
}

会做到这一点。为什么重新发明轮子?

答案 1 :(得分:0)

您的函数打印-1.#IND,因为如果所有检查都失败,则模板函数不返回值(如果所有值都相同则会发生这种情况)。

如果输入的所有值都相同,(param == param2 == param3)将始终评估为false,因为param == param2计算为bool而bool(例如,true)不等于9.0(来自你的例子。)

然后模板方法退出而不返回,并且在打印时会从堆栈中输出垃圾。

你的平等检查应该是第一个:

if ((param == param2) && (param2 == param3))
    return param;

然后你继续检查中间值并且不要忘记在最后else案例中返回一些内容。

说到检查,如果只有2个值相等,那么你的逻辑是有缺陷的。您还应该谨慎直接比较float值,因为某些近似值可能表示为相同的浮点值。