[英]Value is not initialized into the variable in c
這是我制作的程序:
#include <stdio.h>
int main(void)
{
//Put variables here
int space = 0;
int num_of_rows = 0;
int p = 1;
int t = 0;
char alphabet[100] = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
get_and_validate_user_input(num_of_rows);
printf(" The number of rows are : %d", num_of_rows);
}
void get_and_validate_user_input(int num_of_rows)
{
//Input validation
while (1)
{
printf("Enter the number of rows : ");
//Getting the input from the user
scanf("%d", &num_of_rows);
if (num_of_rows <= 0)
{
printf("Negative numbers are not allowed here \n");
}
else
{
break;
}
}
}
預期輸入:輸入行數:5
預期輸出:行數為:5
但是從我的代碼輸出顯示錯誤。 它顯示:行數為:0
現在我的問題是:我的程序出了什么問題? 我怎么解決這個問題?
你的問題是get_and_validate_user_input修改局部變量num_of_rows => 值在main 中保持 0
如果您還想在get_and_validate_user_input 中修改num_of_rows ,請按地址而不是按值給出它,例如(注釋未使用的變量,修改get_and_validate_user_input 中的檢查以與消息兼容):
#include <stdio.h>
#include <stdlib.h>
void get_and_validate_user_input(int * num_of_rows);
int
main(void){
//Put variables here
//int space=0;
int num_of_rows=0;
//int p=1;
//int t=0;
//char alphabet[100]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
get_and_validate_user_input(&num_of_rows);
printf(" The number of rows is : %d\n",num_of_rows);
return 0;
}
void get_and_validate_user_input(int * num_of_rows){
//Input validation
while(1){
printf("Enter the number of rows : ");
//Getting the input from the user
if (scanf("%d",num_of_rows) != 1) {
int c;
puts("Invalid input");
// invalid input, bypass all the line
while ((c = getchar()) != '\n') {
if (c == EOF) {
puts("EOF, abort");
exit(-1);
}
}
}
else if(*num_of_rows < 0){ // 0 seems allowed, else update message
printf("Negative numbers are not allowed here \n");
}
else {
break;
}
}
}
編譯和執行:
/tmp % gcc -Wall c.c
/tmp % ./a.out
Enter the number of rows : 12
The number of rows is : 12
/tmp % ./a.out
Enter the number of rows : aze
Invalid input
Enter the number of rows : -2
Negative numbers are not allowed here
Enter the number of rows : 12
The number of rows is : 12
/tmp %
編譯器沒有看到調用的點
get_and_validate_user_input(num_of_rows);
函數get_and_validate_user_input
是如何聲明的。 所以編譯器發出一條消息。 它期望函數默認具有返回類型int
但當它遇到函數定義時它看到返回類型是void
。
將函數聲明放在 main 之前。
傳遞參數的值未在函數中使用
void get_and_validate_user_input(int num_of_rows){
//...
//Getting the input from the user
scanf("%d",&num_of_rows);
//...
函數參數 num_of_rows 是函數的局部變量,由傳遞的參數值初始化。 所以改變局部變量不會影響原始參數。
您可以像這樣聲明和定義函數
int get_and_validate_user_input( void )
{
int num_of_rows = 0;
//Input validation
while (1)
{
printf("Enter the number of rows : ");
//Getting the input from the user
scanf("%d", &num_of_rows);
if (num_of_rows <= 0)
{
printf("Negative numbers are not allowed here \n");
}
else
{
break;
}
}
return num_of_rows;
}
並在 main 中調用它
num_of_rows = get_and_validate_user_input();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.