线性插值未按预期工作

时间:2016-07-15 04:05:21

标签: c++11 dictionary

我有一张地图,表示给定温度范围内系数Y的值。每当输入键coeff_Y落在键的上限和下限之间的任何地方时,我都试图获得designTemp。我能够得到三种情况:a)当输入designTemp的值低于第一个键时,coeff_Y是第一个值,b)如果输入的值{{1} }超出最后一个键,designTemp是最后一个值,c)如果coeff_Y匹配一个键,则designTemp成为相应的值。如果键落在键范围内的任何位置的情况不起作用。显示插值尝试失败的代码如下所示。请注意,我不是程序员,我是一名管道工程师,只是想编写自己的程序并试图熟练使用C ++编写代码。此外,如果有更好的解决方案,请显示。

coeff_Y

1 个答案:

答案 0 :(得分:0)

有效。我只是犯了愚蠢的错误。它只需要修改if语句的嵌套并添加cout以查找最后else处的插值。下面的代码按预期工作:

#include "../../std_lib_facilities.h"

#include <Windows.h>

#include <map>

int main()

{

SetConsoleTitle(TEXT("PipeTran™_v0.1"));
system("CLS");
system("color F1");

time_t rawtime_start;
struct tm * timeinfo_start;
time(&rawtime_start);
timeinfo_start = localtime(&rawtime_start);
printf(asctime(timeinfo_start));

cout << "\n Enter design temp. in degF: ";
float designTemp;
cin >> designTemp;
map<float, float> ferriticsteels_Y = { { 900, 0.4 },{ 950, 0.5 },{ 1000, 0.7 } };
if (ferriticsteels_Y.find(designTemp) != ferriticsteels_Y.end()) {
    float coeff_Y = ferriticsteels_Y[designTemp];
    cout << "\n Y: " << coeff_Y << endl;
}
else if (designTemp < ferriticsteels_Y.begin()->first) {
    float coeff_Y = ferriticsteels_Y.begin()->second;
    cout << "\n Y: " << coeff_Y << endl;
}
else if (designTemp > ferriticsteels_Y.rbegin()->first) {
    float coeff_Y = ferriticsteels_Y.rbegin()->second;
    cout << "\n Y: " << coeff_Y << endl;
}
else {
    auto lower = ferriticsteels_Y.lower_bound(designTemp) == ferriticsteels_Y.begin() ? ferriticsteels_Y.begin() : --(ferriticsteels_Y.lower_bound(designTemp));
    auto upper = ferriticsteels_Y.upper_bound(designTemp);
    float coeff_Y = lower->second + (upper->second - lower->second) * float(designTemp - lower->first) / fabs(upper->first - lower->first);
    cout << "\n Y: " << coeff_Y << endl;
}

time_t rawtime_end;
struct tm * timeinfo_end;
time(&rawtime_end);
timeinfo_end = localtime(&rawtime_end);
cout << "\n" << asctime(timeinfo_end);

cout << "\nEnter any character and hit enter to exit: ";
char ans;
cin.clear(); cin.ignore(10000, '\n'); cin >> ans;

return 0;

}