我写了这段代码:
std::cout << "When did you graduate? ";
int graduation_year = 0;
std::cin >> graduation_year;
std::cout << "\n";
std::cout << "How much is your student debt? ";
double debt = 0;
std::cin >> debt;
std::cout << "You graduated in " << graduation_year << " and have student debt worth " << debt << ".\n";
double discount = 0;
switch (graduation_year) {
case 2010:
{
if (debt >= 5000 && debt < 10000)
double discount = .99;
double payment = debt …Run Code Online (Sandbox Code Playgroud) 我的程序由于某种原因出现故障,我发现这是因为我的计算结果为pow(-0.2,0.2),当它被调用时,它会解析为-nan(ind).
如果它是一个非常小或非常大的数字我会理解,但为什么C++将此计算解析为-nan(ind)?有没有办法让它输出正确的值(-0.72477966367)?
在我的程序中,我使用了一个随机数生成器.我认为一般规则是你应该将事物定义为接近它们被"调用"的地方,但这对于随机数生成器是否也适用?
例如,在我的代码中,我可以选择:
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_int_distribution<int> uni(-2147483647, 2147483646);
lots of code
for (i = 0; i < 10000; i++)
{
variable x = uni(rng);
}
Run Code Online (Sandbox Code Playgroud)
要么
lots of code
for (i = 0; i < 10000; i++)
{
std::random_device rd;
std::mt19937 rng(rd());
std::uniform_int_distribution<int> uni(-2147483647, 2147483646);
variable x = uni(rng);
}
Run Code Online (Sandbox Code Playgroud)
我会说第一种方法更快,但由于阅读了很多线程,我觉得它总是将所有内容放在靠近它所调用的地方.