首页 > 解决方案 > 使用 C 语言中的函数打印数组的值

问题描述

我对编程很陌生,我正在使用函数打印数组,但遇到了以下错误。

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 个值。就像linspace(0:1:50)在 MATLAB 中一样。

谢谢您的帮助。

标签: arrayscfunction

解决方案


首先,在声明函数中,您不能设置数组的大小。改成

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;
}

推荐阅读