Threaded Program to compute Fibonacci numbers
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: ";
c开发者_开发知识库in >> 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;
}
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;
精彩评论