我不知道问题出在哪里
int main()
{
int antalVarde = 0;
low=0, high=0;
float* arr;
srand((int)time(NULL));
printf("Hur många värden ska skapas: ");
scanf_s("%d", &antalVarde);
printf("Ange min-värde: ");
scanf_s("%d", &low);
printf("Ange max-värde: ");
scanf_s("%d", &high);
arr = (float*)malloc(antalVarde * sizeof(float));
for (int i = 0; i <= antalVarde; i++)
{
*arr = RandomReal(low, high);
}
printf("%f", *arr);
getchar();
return 0;
}
float RandomReal(float low, float high)
{
float d;
d = (float) rand() / ((float) RAND_MAX + 1);
return (low + d * (high - low));
}
答案 0 :(得分:0)
您的循环控制
.json
将打破内存分配的界限,应该是
i <= antalVarde;
但是,每个随机值都使用
写入内存分配的 first 地址i < antalVarde;
和所有其他位置仍包含不确定的值。所以循环应该是
*arr = RandomReal(low, high);
最后,产生编译器警告的原因是,由于没有函数原型,因此编译器假设其为for (int i = 0; i < antalVarde; i++)
{
arr[i] = RandomReal(low, high);
}
类型。因此添加
int
float RandomReal(float low, float high);
之上。
答案 1 :(得分:-1)
这是固定程序:
#include <stdlib.h>
#include <time.h>
float RandomReal(float low, float high);
int main()
{
int antalVarde = 0;
float low = 0, high = 0;
float* arr;
char c;
srand((int)time(NULL));
printf("Hur många värden ska skapas: ");
scanf_s("%d", &antalVarde);
printf("Ange min-värde: ");
scanf_s("%f", &low);
printf("Ange max-värde: ");
scanf_s("%f", &high);
arr = (float*)malloc(antalVarde * sizeof(float));
for (int i = 0; i < antalVarde; i++)
{
arr[i] = RandomReal(low, high);
printf("\nresult[%d] = %f", i,arr[i]);
}
printf("\nHit enter to exit");
c = getchar();
return 0;
}
float RandomReal(float low, float high)
{
float d;
d = (float)rand() / ((float)RAND_MAX + 1);
return (low + d * (high - low));
}