嗯,很明顯,你需要一點幫助。你的功能並不完全符合你期望的功能。對於初學者,您通過num1
和num2
的功能。爲了發生這種情況,他們必須在主要地方宣佈。除了num1
和num2
,您需要聲明變量以保留前兩個函數的返回值,例如sum
和prod
。這些變量也是您將傳遞給CalculateBoth函數的指針的相同變量,以便它們的值在main()
中更新並可用。一個簡單的定義是main()
是所有你需要:
/* declare and initialize variables */
int n1 = 0, n2 = 0, sum = 0, prod = 0;
雖然沒有什麼不對改變一個變量的值的函數,如你的所有功能寫的,你徹底擊垮傳遞num1
的目的, num2
的功能。看起來您打算將num1
和num2
的值傳遞給每個函數,而不是更改函數中的值。例如,在main()
你希望看到:
/* CalculateSum */
n1 = 1, n2 = 2;
sum = CalculateSum (n1, n2);
/* CalculateProduct */
n1 = 3, n2 = 4;
prod = CalculateProduct (n1, n2);
/* CalculateBoth (passing pointer to have value back in main()) */
n1 = 5, n2 = 6;
CalculateBoth (n1, n2, &sum, &prod);
你的任務的剩餘部分是簡單的功能main()
打印值(sum
,prod
,或both
),並再次以確保您已成功更新了函數範圍內的值以及main()
(函數本身)。以下顯示了在函數和main中簡單添加相同的打印語句。如果您有任何問題,請告訴我。
#include <stdio.h>
#define _CRT_SECURE_NO_WARNINGS // I'll take your word for it...
int CalculateSum (int num1, int num2);
int CalculateProduct (int num1, int num2);
void CalculateBoth (int num1, int num2, int *sumPtr, int *prodPtr);
int main(void)
{
/* declare and initialize variables */
int n1 = 0, n2 = 0, sum = 0, prod = 0;
/* CalculateSum */
n1 = 1, n2 = 2;
sum = CalculateSum (n1, n2);
printf (" calculatesum value %d\n", sum);
/* CalculateProduct */
n1 = 3, n2 = 4;
prod = CalculateProduct (n1, n2);
printf (" calc product %d\n", prod);
/* CalculateBoth (passing pointer to have value back in main()) */
n1 = 5, n2 = 6;
CalculateBoth (n1, n2, &sum, &prod);
printf(" calc both sumPtr %d\n", sum);
printf(" calc both prodPtr %d\n", prod);
return 0;
}
int CalculateSum (int num1, int num2)
{
int sum;
sum = num1 + num2;
printf ("\n calculatesum value %d\n", sum);
return sum;
}
int CalculateProduct (int num1, int num2)
{
int prod;
prod = num1 * num2;
printf ("\n calc product %d\n", prod);
return prod;
}
void CalculateBoth (int num1, int num2, int *sumPtr, int *prodPtr)
{
int sum = num1 + num2;
*sumPtr = sum;
int prod = num1 * num2;
*prodPtr = prod;
printf("\n calc both sumPtr %d\n", sum);
printf(" calc both prodPtr %d\n", prod);
}
輸出
如果你的代碼仔細觀察,你會看到正在打印無論是在功能和主同樣的事情:
$ ./bin/fncinmain
calculatesum value 3
calculatesum value 3
calc product 12
calc product 12
calc both sumPtr 11
calc both prodPtr 30
calc both sumPtr 11
calc both prodPtr 30
是你確定這會起作用嗎?寫入時嘗試爲'p [1]'賦值時會發生什麼? –