计算斐波那契数的线程程序

发布于 2024-10-19 16:37:07 字数 1154 浏览 2 评论 0原文

我正在尝试用 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; 
}

I'm trying to write a program in C++ to compute the Fibonacci series. I create a thread that does the calculation and output. But nothing in my for loop seems to get executed. Can anyone have a look at my code and tell me what I might be doing wrong?

#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; 
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

唔猫 2024-10-26 16:37:07

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

You're passing the address of a double to CreateThread, then you try to treat it as an int * in the thread func. Change double x; to int x;

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文