我是C編程的初學者,我需要幫助。 這個c代碼沒有任何錯誤或警告,但我似乎無法讓數組將值傳遞給calcMagicNumber函數。我該如何解決? 在此先感謝!無法將數組傳遞給函數。爲什麼不工作?
#include <stdio.h>
//function prototypes
void printHeader();
void askForNumber();
int calcMagicNumber(int num[], int size);
void writeResults(char*, int, int);
void goodbye();
int main(){
//assign the variables
char name[51]; //for user to input name
char option='Y'; //option for user to continue the program
int magicNumber=0; //to calculate the magic number
int flag=0; //to determine if the magic number is an even or odd number
int num[5]={0,0,0,0,0}; //for user to input the 5 numbers
printHeader();
puts("Please enter your name");
scanf("%[^\n]s", name);
do{
//call the function calcMagicNumber to produce the magic number
magicNumber = calcMagicNumber(num, 5);
//determine if the magic number is an even number
if(magicNumber%2==0){
flag=1;
}
else{
flag=0;
}
//call function writeResults to print out the user's name, the magic
number and whether the magic number is even
writeResults(name, magicNumber, flag);
fflush(stdin); //clear buffer
//ask user if he or she would like to go again
puts("Would you like to go again? [y/n]");
scanf("%c", &option);
option = toupper(option); //to convert the user's input into capital
letters
}while(option == 'Y');
goodbye();
return 0;
}
//function bodies
void printHeader(){
//print out name and chapter 3 - magic number
printf("Chapter 3- Magic Number \n");
printf("Tan Su Fern\n\n");
}
void askForNumber(){
int i=1;
int num[5]={0,0,0,0,0};
//ask user to input number
for(i=1;i<=5;i++){
puts("Please enter a number.");
scanf("%d", &num[i]);
}
num[i]=i;
printf("\n%d, %d, %d, %d, %d", num[1], num[2], num[3], num[4], num[5]);
}
int calcMagicNumber(int num[], int size){
int magicNumber=0;
//call askForNumber function for user to input 5 numbers
askForNumber();
printf("\n%d, %d, %d, %d, %d", num[1], num[2], num[3], num[4], num[5]);
//calculate the magic number based on the numbers input by the user
magicNumber = (num[1]*num[5])-(num[2]+num[3]+num[4]);
return magicNumber;
}
void writeResults(char* name, int magicNumber, int flag){
//print out the magic number and the user's name
printf("\nHi %s , your magic number is %d.\n", name, magicNumber);
//print out if the magic number is an even or odd number
if(flag==1){
printf("This is an even number.\n\n");
}
else{
printf("This is an odd number.\n\n");
}
}
void goodbye(){
//say goodbye
printf("goodbye");
}
你*做*記得數組索引以*零*開始? –
究竟發生了什麼問題?你期待什麼結果,你會得到什麼結果?你如何得出結論:價值觀沒有被通過? – lurker
此外,在C規範中,僅使用輸入流(如stdin)調用'fflush'顯式標記爲* undefined behavior *。有些系統將其添加爲擴展名,但通常不應該這樣做。 –