在我的代码中,我有几个相同的cout
函数,我决定移出int main()
。
但是,当我这样做并重新运行我的代码时,当触发有问题的函数时,我收到“Debug Assertion Failed”错误。
我在主要功能之外放置的代码。
string printresult(double smallest, double largest)
{
cout << "the smaller value is: " << smallest << "\n";
cout << "the larger value is: " << largest << "\n";
return 0;
}
我认为它与我在return 0
函数末尾添加的cout
代码有关,但是没有它,我的代码现在甚至编译了。任何人都可以指向正确的方向,以便我能更好地识别我的错误吗?
我的完整代码
#include "../../std_lib_facilities.h"
// conversion of units to meters
double funconvert(double x, string unit)
{
const double cm_m = 1.0 / 100.0, in_cm = 2.54, ft_in = 12;
if (unit == "m")
return x = x;
else if (unit == "cm")
return x = x * cm_m;
else if (unit == "in")
return x = x * in_cm * cm_m;
else if (unit == "ft")
return x = x * ft_in * in_cm * cm_m;
else
cout << "Unknown unit value.\n";
}
// printing the large and the small variables
string printresult(double smallest, double largest)
{
cout << "the smaller value is: " << smallest << "\n";
cout << "the larger value is: " << largest << "\n";
return 0;
}
int main()
{
vector<double>numbers;
double a, b, smallest, largest;
string unit;
cout << "Please enter an intiger followed by a measurment unit [e.g 10cm]:";
// Take input
while (cin >> a >> unit)
{
// check if this is the first number entered
if (numbers.size() == 0)
{
a = funconvert(a, unit);
b = a;
numbers.push_back(a);
numbers.push_back(b);
}
else
{
//assign a and b to the last two numbers in a vector
a = funconvert(a, unit);
numbers.push_back(a);
a = numbers[(numbers.size() - 1)];
b = numbers[(numbers.size() - 2)];
// numbers.erase(numbers.begin()); // enable if desire to keep the vector empty
}
// find out which variable is larger and smaller
if (a > b && (a/b-1) >= 0.01)
{
smallest = b;
largest = a;
printresult(smallest, largest);
}
else if (a < b && (b / a - 1) >= 0.01)
{
smallest = a;
largest = b;
printresult(smallest, largest);
}
else if ((a / b - 1) < 0.01 && (a / b - 1) != 0.00 || (b / a - 1) < 0.01 && (a / b - 1) != 0.00)
{
cout << "the nubers are almost equal\n";
}
else
cout << a << " equals " << b << "\n";
}
return 0;
}
答案 0 :(得分:1)
您的printresult
会返回您初始化为0的std::string
。它会调用以下构造函数
basic_string( const CharT* s,
const Allocator& alloc = Allocator() );
除了有效的缓冲区地址之外,它是undefined behavior传递的。
构造字符串,其中包含使用。的副本初始化的内容 s指向的以null结尾的字符串。的长度 string由第一个空字符决定。行为是 如果s没有指向至少一个数组,则为undefined Traits :: length(s)CharT的+1个元素,包括s是a的情况 空指针。
认为自己很幸运,你的标准库实现就是这样。
答案 1 :(得分:1)
当您编写return 0
时,C ++标准库会尝试使用std::string
中的const char*
构造函数。但是该构造函数要求您为以空值终止的字符缓冲区提供有效地址,否则程序行为 undefined 。
要修复此问题,请将该功能更改为void
返回类型:
void printresult(double smallest, double largest)
并将return
语句放在函数体中。
还可以考虑将特殊return x = x;
替换为return x;