簡體   English   中英

使用C語言中的函數打印數組的值

[英]Printing values of an array using a function in C language

我對編程很陌生,我正在使用函數打印數組,但遇到以下錯誤。

Test.c: In function ‘main’:

Test.c:21:54: error: incompatible type for argument 1 of ‘theta’
21 |  printf("The theta values are = %lf\n", x[i], theta(x[i]));
   |                                                     ~^~~
   |                                                      |
   |                                                      double
Test.c:5:21: note: expected ‘double *’ but argument is of type ‘double’
5 | double theta(double x[N])
  |              ~~~~~~~^~~~

這是代碼。

#include <stdio.h>
#include <stdlib.h>

#define N 50

double theta(double x[N]);

int main(){
    int i;   
    double x[i];

    printf("The theta values are = %lf\n", x[i], theta(x[i]));
    return 0;
}

double theta(double x[N]){
    int i;

    for(i = 0; i < 50; i++){
        x[i] = (double)(i)/ ((double)(N) - 1.0);
    }
    return x[i];
}

我只想打印 0 到 1 之間的 50 個值。就像 MATLAB 中的linspace(0:1:50)

謝謝您的幫助。

首先,在聲明函數中,您不能設置數組的大小。 改成

double theta(double* X)

其次,做 double theta(double x[N]); 在主函數中。

這是編譯器沒有建議你,但我在你的代碼中發現了錯誤。

首先,theta 中的 i 與 main 中的 i 不同

二、 for打印

我想你想要這個代碼

#include<stdio.h>
#include<stdlib.h>
#define N 50

double* theta()
{
  int i;
  double x[N];
  for(i = 0; i < N; i++){
  x[i] = (double)(i)/ ((double)(N) - 1.0);
 }
 return x;
}


int main(){
 int i;   
 double* x=theta();
 for(i=0;i<N;i++){
    printf("The theta values are = %lf\n", x[i]);
 }
 return 0;
}  

我更喜歡這個代碼

#include<stdio.h>
#include<stdlib.h>
#define N 50

int main(){
    int i;
    for(i=0;i<N;i++){
        printf("%lf\n",i/(N-1.0));
    }
    return 0;
}

我找到了解決方案。 這里是。

#include <stdio.h>
#include <stdlib.h>

#define N 50

double* theta(double x[], int nb_elements){
    int i;

    for(i = 0; i < nb_elements; i++){
        x[i] = (double)(i)/ ((double)(nb_elements) - 1.0);
    }
    return &x[0];
}

int main(){
    int i;   
    double x[N];

    theta(x, N);

    for(i = 0; i < N; i++){
        printf("%lf\n", x[i]);
    }
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM