【发布时间】:2012-05-29 19:36:16
【问题描述】:
我编写了一个程序,它从用户那里获取数字,然后允许输入数字,然后创建两个线程,一个用于计算总和,另一个用于计算 Avg 但是在给出数字后程序停止并给出错误为什么?
#include<stdio.h>
#include<Windows.h>
#include<stdlib.h>
int count ;
DWORD WINAPI Sum(PVOID s)
{
int *sum=(int *)s;
DWORD c=0;
for(int i=0;i<count;i++)
c+=sum[i];
return c;
}
DWORD WINAPI Avg(PVOID s)
{
int *var=(int *)s;
DWORD avg=0;
avg=(*var/count);
return avg;
}
int main()
{
printf("Enter the number of numbers\n");
scanf("%d",&count);
int *s = (int*)malloc(sizeof(int)*count);
printf("now enter the numbers\n");
for(int i=0;i<count;i++)
scanf("%d",s[i]);
HANDLE t1 , t2;
DWORD id1 , id2 , c1 , c2;
t1 = CreateThread(NULL , 0 , Sum , s , 0 , &id1);
WaitForSingleObject(t1,INFINITE);
GetExitCodeThread(t1 , &c1);
printf("The Sum = %d", c1);
t2 = CreateThread(NULL , 0 , Avg , (PVOID*)&c1 , 0 , &id2);
WaitForSingleObject(t2,INFINITE);
GetExitCodeThread(t2 , &c2);
printf("The AVgerage = %d", c2);
return 0;
}
如果有人能帮助我,将不胜感激。 谢谢 所以 T 更新程序,现在它可以工作了,但是 Avg 是错误的,那是因为当我尝试像这样 printf("The AVG=%f\n",c2) 打印它时结果为零 为什么?
【问题讨论】:
-
请在此问题中添加语言标签。我假设 C++?
标签: c multithreading winapi