[英]random and pointers doesn't work
您好,我試圖將浮點數增加到Pointer,但是不知何故,程序始終打印0.00000。 該數字應介於12.01到-13.00之間。
我的代碼-
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
float* num = (float*)malloc(sizeof(float));
srand(time(NULL));
*num = rand() % 1300 + 1201 / 100.00;
printf("%f",num);
system("PAUSE");
free(num);
}
如果有人可以幫助我解決該問題,我將非常感謝。
如果要在打印地址時打印號碼,請注意*:
printf("%f",*num);
您需要打印num指向的值:
printf("%f", *num);
兩件事情:
malloc
為C語言(與您的問題無關,但還是個好主意 ) 這兩件事都可以幫助您避免問題。 用gcc -Wall
編譯gcc -Wall
我得到:
警告:格式'%f'期望類型為'double'的參數,但是參數2的類型為'float *'[-Wformat =] printf(“%f”,num);
那會回答你的問題。 您正在使用%f
格式說明符,但傳遞的是指針,而不是float
或double
。 您需要取消引用指針:
printf("%f", *num);
這些是錯誤:
*num = rand() % 1300 + 1201 / 100.00;
*num
在[12.01,1311.01]范圍內。 如果需要[12.01,13.00]范圍內的數字,請更改分配:
*num = 12.01 + (rand() % 100) / 100.0;
printf("%f", num);
應該是printf("%f", *num);
另外,在編譯過程中啟用額外的警告也是一個好主意。 例如-Wall -Wextra
clang -Wall -Wextra filename.c
warning: format specifies type 'double' but the argument has type 'float *' [-Wformat]
與gcc相同
gcc -Wall -Wextra filename.c
warning: format '%f' expects argument of type 'double', but argument 2 has type 'float *' [-Wformat=]
如果您正在使用malloc
/ free
,則應檢查分配失敗。
不能保證內存分配成功,而是可以返回空指針。 如果不檢查是否實現了成功的分配,這通常會導致程序崩潰,因為在空指針取消引用上會導致分段錯誤。
因此,您可以通過以下方式更改代碼:
float *num = malloc(sizeof(float));
if (num)
{
// your code
}
else
{
// handle failure
}
無論如何,最好只使用一個簡單的浮點數。
除了修復printf("%f", *num);
,您需要檢查一下數學!
如果您確實希望結果在12.01到-13.00之間,
*num = (rand() % 2501 - 1300) / 100.00;
你程序調用未定義的行為,因為num
是不是float
,但一個指向float
和你試圖打印它作為一個float
的%f
轉換說明在printf
調用。 另外,不要轉換malloc
的結果,而在main
的參數列表中明確提及void
。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
float *num = malloc(sizeof *num);
srand(time(NULL));
*num = rand() % 1300 + 1201 / 100.00;
printf("%f", *num); // note *num instead of num
system("PAUSE");
free(num);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.