[英]Function not returning integer value (C)
So I have this code, when I print N it comes out as 0, can someone explain to me why this is happening and how to avoid it?所以我有这段代码,当我打印 N 时它显示为 0,有人可以向我解释为什么会发生这种情况以及如何避免它吗?
#include <stdio.h>
#include <math.h>
int enter(char[],int);
int main(void){
int N,M,i,j,f=1;
double C=0;
enter("Enter number N: ",N);
printf("%d",N);
return 0;
}
int enter(char s[], int a){
do{
printf("%s",s);
scanf("%d",&a);
}while(a<1||a>15);
return a;
}
The signature of enter
is confusing: trying to pass it an integer
suggests that you want to store the input inside, whereas the integer
returned suggests that user should store it. enter
的签名令人困惑:尝试将integer
传递给它表明您要将输入存储在其中,而返回的integer
表明用户应该存储它。
So the two ways are:所以这两种方式是:
To store inputs in your actual N
, use an int*
parameter:要将输入存储在您的实际
N
中,请使用int*
参数:
enter("Enter number N:", &N); // in main()
void enter(char s[], int* Np) // note void function
{
// ...
scanf("%d", Np); // writes input at memory adress of variable N from main()
// ...
}
To use the value returned by the function to store it in N
:要使用 function 返回的值将其存储在
N
中:
N = enter("Enter N:"); // in main()
int enter(char s[]) // note no integer parameter
{
int n;
// ...
scanf("%d", &n);
// ...
return n;
}
You need to save the value returned by the enter function into 'N'需要将输入function返回的值保存成'N'
Like this像这样
N = enter("Enter number N: ",N);
Also initialize 'N' to something like N=0, as by default N will be a garbage value.还将“N”初始化为 N=0,因为默认情况下 N 将是一个垃圾值。
Or You can pass 'N' by reference instead of value或者您可以通过引用而不是值传递“N”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.