在我的代码中,我有几个地方有一个相同的 cout
函数,我决定将其移到 int main()
之外。
然而,当我这样做并重新运行我的代码时,当相关函数被触发时,我收到了“调试断言失败”错误。
我放在主函数之外的代码。
string printresult(double smallest, double largest)
{
cout << "the smaller value is: " << smallest << "\n";
cout << "the larger value is: " << largest << "\n";
return 0;
}
我相信它与我在 cout
函数末尾添加的 return 0
代码有关,但是如果没有它,我的代码现在可以甚至编译。任何人都可以指出我正确的方向,以便我可以更好地识别我的错误吗?
我的完整代码
#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;
}
最佳答案
当您编写return 0
时,C++ 标准库会尝试使用来自const char*
的std::string
构造函数。但是该构造函数要求您向以 nul 结尾的字符缓冲区提供有效地址,否则程序行为未定义。
要修复,请将函数更改为 void
返回类型:
void printresult(双最小,双最大)
并将 return
语句放入函数体中。
还可以考虑用 return x;
return x = x;
关于c++ - cout 函数调试断言失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40467498/