arrays - 使用 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 中一样。
谢谢您的帮助。
解决方案
首先,在声明函数中,您不能设置数组的大小。改成
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;
}
推荐阅读
- canvas - 如何将风玫瑰图嵌入 GUI
- user-interface - Tkinter:小部件未应用于屏幕的右上角(网格)
- javascript - Material ui v4:我想使用类型脚本在类组件内自定义一个 Material UI 按钮。请让我知道我该怎么做?
- python - Pandas:根据列总和选择列
- scala - 在 Slick 中一次和多次调用“run.db”有什么区别吗
- laravel - 无法调用组件方法。在组件上找不到公共方法 [storeLike]:
- php - laravel rest api 有时会抛出 socket hang up 或 ECONNRESET 错误
- date-fns - MM 和 mm 有什么区别,为什么没有 DD 而不是 dd 用于 date-fns
- mysql - 如果另一个表中存在值,如何插入到表中
- ios - 主线程在swift 5中冻结后台线程操作