c++ - 将 if 中的一个值复制到另一部分

标签 c++ if-statement

你好,我想复制一个我在 if 中得到的值,这样我就可以在代码的下一部分使用它,我该怎么做?我不能在 elapsed_secs 部分使用 begin 的值谢谢

int temp = temp + 1;
if (temp == 1)
    clock_t begin = clock();
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;
gotoxy(50, 1); printf("Tiempo: %d", elapsed_secs);

最佳答案

像这样:

int temp = <insert-initial-value>; // in your code it's used uninitialized!!!
clock_t begin = <insert-initial-value>;
if (temp == 1)
    begin = clock();
clock_t end = clock();
double elapsed_secs = double(end - begin) / CLOCKS_PER_SEC;

因为您希望 begin 的范围在 if 语句的主体之外。

此外,您需要为 begin 提供一个初始值,以便在计算 elapse_secs 时不会使用未初始化的值(这将调用未定义的行为)。


编辑:

根据您的评论,我相信这就是您想要做的(基于我的 Time measurements ):

#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>

void functionToBeTimed(void) {/*do something here*/}

int main ()
{
  using namespace std::chrono;

  high_resolution_clock::time_point t1 = high_resolution_clock::now();

  std::cout << "Executing the function twice...\n";
  for (int i = 0; i < 2; ++i)
    functionToBeTimed();

  high_resolution_clock::time_point t2 = high_resolution_clock::now();

  duration<double> time_span = duration_cast<duration<double>>(t2 - t1);

  std::cout << "It took me " << time_span.count() << " seconds." << std::endl;

  return 0;
}

关于c++ - 将 if 中的一个值复制到另一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47524942/

相关文章:

c++ - 为什么在 C++ 中经常使用 "out variable pattern"?

java - 按键输入限制

arrays - Powershell:如果 array1 中的项目包含 array2 中的项目,我在这里做错了什么

if-statement - if_/3 有什么用?

C++数字计数奇怪的错误

c++ - 为什么 STL 中没有针对每个集合类型的 for_each 成员函数?

excel - 尝试具有一系列可能结果的 Excel IF 语句

javascript - 检查所选元素是否包含属性

c++ - 科学计数法数字的正则表达式?

c++ - 绑定(bind)错误 : Address already in use