【问题标题】:Threaded Program to compute Fibonacci numbers计算斐波那契数的线程程序
【发布时间】:2011-02-28 11:41:16
【问题描述】:

我正在尝试用 C++ 编写一个程序来计算斐波那契数列。我创建了一个执行计算和输出的线程。但是我的 for 循环中似乎没有任何东西被执行。谁能看看我的代码并告诉我我可能做错了什么?

#include <iostream>
#include <Windows.h>
#include <stdio.h>
#include <stdlib.h>

using namespace std; 

//iterative with output
DWORD WINAPI fib3(LPVOID param){
double u = 0; 
double v = 1;
double t; 
int upper = *(int*)param;

for(int i = 2; i <= upper; i++){
    cout << v << " "; 
    t = u + v; 
    u = v; 
    v = t; 
    cout << "testing" << endl; 
}
    cout << v << " "; 
    return 0; 
}

int main(int argc, char *argv[]){

cout << "This will compute the fibonacci series.\n" << endl; 
bool done = true; 
double x; 
DWORD ThreadId; 
HANDLE ThreadHandle; 

while(done){

    cout << "Enter a number: "; 
    cin >> x;

    if(x == -1){
        cout << "\nExiting" << endl; 
        return 0; 
    }

    ThreadHandle = CreateThread(NULL, 0, fib3, &x, 0, &ThreadId); 

    if(ThreadHandle != NULL){
        WaitForSingleObject(ThreadHandle, INFINITE); 

        CloseHandle(ThreadHandle); 
    }

}

return 0; 
}

【问题讨论】:

  • 选择done 作为变量名,您将获得梦寐以求的混淆奖(三等奖)。
  • 与您的问题没有直接关系,但使用循环计算斐波那契数是一种相当低效的方法。您使用这种方法有什么原因吗?
  • 我知道我可以递归地做到这一点。但我只是觉得这样输出每个数字会更容易?
  • 递归也不是一个好方法(它只在教授递归时在学术上真正有用)。有计算斐波那契数的公式。见mathworld.wolfram.com/BinetsFibonacciNumberFormula.html
  • @ZacHowland 我会犹豫使用这个公式,因为它涉及容易出现舍入错误的浮点运算。请参阅wandbox.org/permlink/Kitb6mbkRODXbElS,其中使用double 时的结果是不同的,例如,Fib(90)。 IMO,更好的解决方案是使用精确计算的斐波那契数表,因为标准整数类型只能表示其中的几个。

标签: c++ multithreading fibonacci


【解决方案1】:

您将 double 的地址传递给 CreateThread,然后您尝试将其视为线程函数中的 int *。将double x; 更改为int x;

【讨论】:

  • 感谢您的快速响应。做到了:-D
猜你喜欢
  • 1970-01-01
  • 2020-03-09
  • 2013-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-06
  • 2020-01-18
相关资源
最近更新 更多