我的程序应该以数组形式显示 R1=x、R2=x、R3=x 的情况。然后计算串联电阻的等效电阻。所有值均由用户提供。我的问题是,我认为它没有正确地将函数传递给equivRseries。在输出上,它允许我输入电阻器的数量,但是一旦我输入电阻值,它就不会让我输入其余电阻器的值。我可以得到一些帮助吗?这是我的代码:
#include <stdio.h>
#include <math.h>
#define max 100
void equivRseries(float R[max], float N, float *xPtr);
void input (float *xPtr, float R[max], float N){
int i;
printf("Please enter how many resistors you want in series: ");
scanf("%d", &N);
for(i=0; i<N; i++){
printf("Enter the value of R%d: ", i+1);
scanf("%f", &R[i]);
}
for(i=0; i<N; i++){
printf("R[%d]=%.2f\n", i+1, *(xPtr+i));
}
equivRseries(R, N, xPtr);
}
void equivRseries(float R[max], float N, float *xPtr){
int i;
float equivR=0;
for(i=0; i<N; i++){
equivR=equivR+*(xPtr+i);
}
printf("Equivalent resistance of this circuit is %f\n", equivR);
}
int main(){
float R[max], series, N;
float *xPtr;
xPtr=R;
input(xPtr,R,N);
return 0;
}
最佳答案
这里:
scanf("%d", &N);
N
的类型为 float
,因此 &N
的类型为 float*
。但 %d
需要一个 int*
,而不是 float*
。这会调用未定义的行为。
通过将格式说明符更改为 %f
或将 N
的类型更改为 int
来修复此问题。
顺便说一句,为什么将 N
传递给函数而不是在函数中声明它是没有意义的。另外,也不需要xPtr
。您可以直接使用R
而不是xPtr
。
如果您将警告(至少使用 -Wall
)编译为 @hexasoft has said below ,您就会注意到这个问题。 GCC 给出:
source_file.c: In function ‘input’:
source_file.c:8:2: warning: format ‘%d’ expects argument of type ‘int *’, but argument 2 has type ‘float *’ [-Wformat=]
scanf("%d", &N);
^
关于c - 为什么我的程序在 C 语言下不能正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33654568/