gpt4 book ai didi

c++ - int 到 unsigned int 的无效转换

转载 作者:行者123 更新时间:2023-11-28 07:42:13 29 4
gpt4 key购买 nike

此代码是为作业提供的。但是,马上就出现了计算 pi 蒙特卡洛函数中的错误。从 int 到 unsigned int 的转换错误统计信息无效。我不确定这是否有意为之,但我无法更正此问题。如果您想知道,此函数是线程示例的一部分。非常感谢任何建议

void *compute_pi( void *s )   
{
int seed;
int ii;
int *hit_pointer;
int local_hits;
double rand_no_x;
double rand_no_y;

hit_pointer = (int *) s;
seed = *hit_pointer;
local_hits = 0;

for( ii=0; ii < sample_points_per_thread; ii++ )
{
rand_no_x = (double) (rand_r( &seed ))/(double)RAND_MAX;//*error is these lines
rand_no_y = (double) (rand_r( &seed ))/(double)RAND_MAX;//*error is these lines
if(((rand_no_x - 0.5) * (rand_no_x - 0.5) +
(rand_no_y - 0.5) * (rand_no_y - 0.5)) < 0.25)//*error
local_hits++;
seed *= ii;
}

*hit_pointer = local_hits;
pthread_exit(0);
}

我做了一些调试,现在看看错误可能在哪里。我现在发布调用 compute pi 的主要函数。我相信这是将参数解析为样本点和线程数的地方。当我运行该程序时,它要求输入,但由于段错误而失败。有什么建议吗?

  #include <pthread.h>
#include <stdlib.h>
#include <stdio.h>

#define MAX_THREADS 512

void *compute_pi( void * );


int sample_points;
int total_hits;
int total_misses;
int hits[ MAX_THREADS ];
int sample_points_per_thread;
int num_threads;



int main( int argc, char *argv[] )
{
/* local variables */
int ii;
int retval;
pthread_t p_threads[MAX_THREADS];
pthread_attr_t attr;
double computed_pi;

/* initialize local variables */
retval = 0;


pthread_attr_init( &attr );
pthread_attr_setscope( &attr, PTHREAD_SCOPE_SYSTEM );

printf( "Enter number of sample points: " );
scanf( "%d", &sample_points );
printf( "Enter number of threads: " );
scanf( "%d%", &num_threads );

/* parse command line arguments into sample points and number of threads */
/* there is no error checking here!!!!! */
sample_points = atoi(argv[1]);
num_threads = atoi(argv[2]);


total_hits = 0;
sample_points_per_thread = sample_points / num_threads;

for( ii=0; ii<num_threads; ii++ )
{
hits[ii] = ii;
pthread_create( &p_threads[ ii ], &attr, compute_pi, (void *) &hits[ii] );
}

for( ii=0; ii<num_threads; ii++ )
{
pthread_join( p_threads[ ii ], NULL );
total_hits += hits[ ii ];
}

computed_pi = 4.0 * (double) total_hits / ((double) (sample_points));


printf( "Computed PI = %lf\n", computed_pi );


/* return to calling environment */
return( retval );
}

最佳答案

来自rand_r(3) man page :

int
rand_r(unsigned *ctx);

如您所见,它需要一个 unsigned 指针 - 如果您将一个 int 传递给它并且您在编译器中打开了适当的警告/错误(并且它似乎你这样做了),你会得到那个错误。更改 seed 的类型,您将被设置。

关于c++ - int 到 unsigned int 的无效转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15582865/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com