[英]scanf() to 1D array in C
我在從終端讀取用戶輸入到我的數組時遇到問題。
數組“ a”具有動態大小。 用戶輸入的多項式確定數組的大小。
一旦編譯並運行:
Enter the order number:
3
Enter your constant:
-90
Enter coefficient # 0
8
Enter coefficient # 1
4
Enter coefficient # 2
35
Enter coefficient # 3
54
0 8.000000
1 4.000000
2 0.000000
3 0.000000
在調試行中,我只是將陣列報告給用戶。 由於某些原因,它在數組的后半部分返回零。 我不知道可能是什么問題。 任何幫助將不勝感激。
PS。 忽略eval函數。
這是我正在處理的代碼:
//import required libraries
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// function prptotype
double eval(double a[], double x, int n); //n is max degree
//global variables
int N = 0;//N is the polynomial order
double *a;//array
double x; // constant
//main function
int main()
{
printf("%s\n", "Enter the order number:");
scanf("%d", &N); // user input for the order numbers
while (N < 1) //input debuger
{
printf("%d %s\n%s\n", N,"is NOT a positive and non-zero number", "Enter a positive and non-zero integer:" );
scanf("%d", &N); // user input for the order numbers
}
a = malloc ((N + 1) * sizeof(int));// assigning the array size in respect with user input
printf("%s\n", "Enter your constant:" );
scanf("%lf", &x);// user input for "x" constant
for (int i = 0; i < N + 1; ++i)
{
printf("Enter coefficient # %d\n", i);
scanf ("%lf", &a[i]);
}
/* Debug */
for (int i = 0; i < N + 1; ++i)
{
//a[i] = 0;
printf("%3d%13lf\n", i, a[i]);
}
}
//eval function
double eval(double a[], double x, int n)
{
}
第一個問題是-
a = malloc ((N + 1) * sizeof(int)); //you allocate for N+1 integers
您沒有分配足夠的內存(您需要分配N+1
double
)。 a
是double *
sizeof(int)
double *
,您可以使用sizeof(int)
。 更正為-
a = malloc ((N + 1) * sizeof(double));
和打印的東西double
用途%f
不會%lf
(僅適用於scanf
) -
printf("%3d%13lf\n", i, a[i]); // -> use %f
^^
注意 -不要忘記free
分配的內存。 而且BTW在您的代碼中沒有數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.