简体   繁体   English

scanf()到C中的一维数组

[英]scanf() to 1D array in C

I'm having problems reading user inputs from terminal into my array. 我在从终端读取用户输入到我的数组时遇到问题。

the array 'a' has a dynamic size. 数组“ a”具有动态大小。 The polynomial which is inputted by the user determines the size of the array. 用户输入的多项式确定数组的大小。

once compiled and run: 一旦编译并运行:

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

On the debug lines I'm just reporting the array back to user. 在调试行中,我只是将阵列报告给用户。 For some reasons it returns zero for the second half of the array. 由于某些原因,它在数组的后半部分返回零。 I can't figure out what the problem could be. 我不知道可能是什么问题。 Any help would be greatly appreciated. 任何帮助将不胜感激。

PS. PS。 ignore eval function. 忽略eval函数。

here is the code I'm working on: 这是我正在处理的代码:

//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)
{

}

First problem is this - 第一个问题是-

a = malloc ((N + 1) * sizeof(int));  //you allocate for N+1 integers

You don't allocate enough memory(you need to allocate for N+1 double ) . 您没有分配足够的内存(您需要分配N+1 double )。 a is a double * and you use sizeof(int) . adouble * sizeof(int) double * ,您可以使用sizeof(int) Correct it to - 更正为-

a = malloc ((N + 1) * sizeof(double));

And thing for printing double use %f not %lf (only for scanf )- 和打印的东西double用途%f不会%lf (仅适用于scanf ) -

printf("%3d%13lf\n", i, a[i]); // -> use %f
              ^^

Note - Don't forget to free allocated memory. 注意 -不要忘记free分配的内存。 And BTW no array in your code . 而且BTW在您的代码中没有数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM