开发者

Floating point number generation in C on Montavista on PPC

开发者 https://www.devze.com 2023-02-27 02:13 出处:网络
I have the following simple program to generate floating point random numbers between 1 and 4: #include<stdio.h>

I have the following simple program to generate floating point random numbers between 1 and 4:

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

main()
{
    int i = 0;
    float u;

        srand((unsigned)time(NULL));
        for(i = 0;i< 10000 ; i++)
        {
            u =  ((4-1)*((float)rand()/RAND_MAX))+1;
            printf("The random value for iteration = %d is %2.4f \n", i, u);
        }
}

It succes开发者_运维知识库sfully generates floating point random numbers between 1 and 4 on an x86 Red Hat Linux machine. But the same program produces 0.0000 as random number on a PPC running Montavista Linux.

Could someone explain why and how to make this work on the PPC Montavista ?


A hunch is that you should be using double instead of float or printing (double)u, since %f takes a double. I was under the impression that floats were automatically promoted to double when passed to a vararg function though.

You could also try printing (int)(u*10000).

0

精彩评论

暂无评论...
验证码 换一张
取 消