我想知道如何在 C语言
中生成精确到最多6点小数且在(-999到+999)范围内的随机浮点数位我尝试过:
unsigned int i, num;
int divide;
FILE *f;
f=fopen("/dev/urandom", "r");
if (!f) {
fprintf(stderr, "Failed open file\n");
exit(1);
}
for(i=0; i< w*w; i++)
{
fread(&num, sizeof(unsigned int), 1, f);
fread(÷, sizeof(int), 1, f);
h[i] = ((float)num)/((float)divide);
}
fclose(f);
但这会产生超过6个小数点。
有没有办法获得浮动没有。例如。 34.123456000000000000000,即在小数点后6位,应截断该值的其余部分。
@sas @Havenard @Lundin标记为重复的问题仍然无法解决问题。代码:
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
void fill(float* h, int w)
{
unsigned int i, num;
int divide;
FILE *f;
f=fopen("/dev/urandom", "r");
if (!f)
{
fprintf(stderr, "Failed open file\n");
exit(1);
}
for(i=0; i< w*w; i++)
{
fread(&num, sizeof(unsigned int), 1, f);
fread(÷, sizeof(int), 1, f);
h[i] = ((float)num)/((float)divide);
h[i] = trunc(100*h[i])/100; // trial for 2 place decimal
}
fclose(f);
}
void getrand(int n )
{
const int mybatch = 1;
float mat1_size = sizeof(float) * n * n;
float* mat1 = (float*) malloc(mat1_size);
fill(mat1, n);
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
fprintf(stdout,"%12.10f ",mat1[i*n+j]);
}
fprintf(stdout,"\n");
}
fprintf(stdout,"\n\n");
}
int main(int argc, char *argv[])
{
if(argc!=2)
{
printf("Usage: %s <matrix_width>\n", argv[0]);
return 0;
}
int w;
w = atoi( argv[1] );
getrand(w);
return 0;
}
仍会打印:
$ ./a.out 5
-2.2799999714 3.5999999046 15.5200004578 -0.9900000095 -1.3099999428
-1.8799999952 1.4700000286 2.0499999523 0.4900000095 2.0499999523
0.9599999785 -0.4199999869 -0.4499999881 4.3200001717 -0.7699999809
-2.9300000668 2.5099999905 -1.5900000334 -0.4199999869 -0.6800000072
-0.2300000042 -1.7599999905 3.1800000668 0.6000000238 0.6000000238
答案 0 :(得分:1)
您可以尝试使用trunc功能。
可能你看起来像这样。举个例子。
float a = 34.123456000000000000000;
a = trunc(1000000*a)/1000000;
printf("%f\n", a);// output = 34.123455
注意 - 请在程序中加入math.h
标题
How to truncate a floating point number after a certain number of decimal places (no rounding)?
可能重复