首页 > 解决方案 > c++,cin的问题?

问题描述

我写了一个小测试来找出特殊 x 的最快数学运算。我希望用户输入 x,以便我可以针对不同的 x 运行测试。在下面的代码中,我告诉我std::cin >> val; 存在错误。错误:无法将“std::istream {aka std::basic_istream}”左值绑定到“std::basic_istream&&”

如果我声明 valdouble val而不是const double val我会得到更多错误。为了有一个正在运行的程序,我可以改变什么?

#include <cmath>
#include <chrono>
#include <iomanip>
#include <iostream>
#include <istream>
#include <ostream>
// for x^1.5 
double test_pow_15(double x) { return std::pow(x, 1.5); };
double test_chain_15(double x) { return sqrt(x * x * x); };
double test_tmp_15(double x) { double tmp = x * x * x; return sqrt(tmp); };


volatile double sink;
const double val = 0;
const double ans_15 = std::pow(val, 1.5);

void do_test(const char* name, double(&fn)(double), const double ans) {
    auto start = std::chrono::high_resolution_clock::now();
    for (size_t n = 0; n < 1000 * 1000 * 10; ++n) {
        sink = val;
        sink = fn(sink);
    }
    auto end = std::chrono::high_resolution_clock::now();
    std::chrono::duration<double, std::milli> dur = end - start;
    std::cout << name << ".Took" << dur.count() << "ms, error:" << sink - ans << '\n';
}

int main()
{
    std::cout << "Speed test"<< '\n';
    std::cout << "Please enter value for x."<< '\n';
    std::cout << "x = ";
    std::cin >> val;

    std::cout << "Speed test starts for x = "<< val <<"."<<'\n';
    std::cout << " " << '\n';
    std::cout << "For " << val<<"^(1.5) the speed is:" <<'\n';
    do_test("std::pow(x,1.5)                                  ",test_pow_15, ans_15);
    do_test("sqrt(x*x*x)                                      ",test_chain_15, ans_15);
    do_test("tmp = x*x*x; sqrt(tmp)                           ",test_tmp_15, ans_15);

    return 0;
}

标签: performancec++11testingcmath

解决方案


我认为如果您删除“const”关键字,它可能会正常工作。

双倍价值 = 0;


推荐阅读