首先,我對編程很陌生,這是我在這里的第一個問題。我正在創建一個代碼來計算梯形的面積,我需要做同樣的while()3 次不同的時間來檢查數字是否大于零,如果不是,它會一直詢問數字直到它是. 然后我決定創建一個function()以使代碼干凈且重復性更少,問題是,我可能做錯了什么,因為我只將負數回傳給變數。
我將部分代碼展示給你們看,也用于測驗。我總是先輸入一個負數來激活while()內部function(),然后我輸入一個正數,但我列印的是負數而不是新數字。關于如何在 largeBase 變數中獲取新數字的任何提示?這是代碼:
#include <stdio.h>
int checkBelowZero(float x);
int main() {
float largerBase, x;
printf("\n\t\tTrapezoid's area calculation\n\n");
printf("Type the trapezoid's larger base: ");
scanf("%f", & largerBase);
checkBelowZero(largerBase);
printf("%.2f", largerBase);
return 0;
}
int checkBelowZero(float x) {
while (x <= 0)
{
printf("\nThe number has to be greater than zero (0).\n\nPlease, type it again: ");
scanf("%f", & x);
}
return x;
}
uj5u.com熱心網友回復:
解決方案 1
函式引數是給定值的副本。如果您修改引數的值,您實際上并沒有修改傳遞的原始變數。
但是,當通過參考傳遞時,情況并非如此。如果將變數的地址傳遞給函式,然后呼叫指向該地址的指標,則可以修改傳遞的變數的真實值。我已經重寫了有問題的函式,所以你可以看到它是如何作業的:
// the parameter is expecting a pointer to something
void checkBelowZero(float *x) {
/*- to read the parameters value, call a pointer to it
- "x" is actually just a number which is the memory
location of the variable you passed. Calling a pointer
to it reads what's at that address, in this case the
value of your variable "largerBase".
*/
while (*x <= 0)
{
printf("\nThe number has to be greater than zero (0).\n\nPlease, type it again: ");
/* - Since "x" already contains the base address of
"largerBase", you shouldn't call the base address of
that
*/
scanf("%f", x);
}
}
確保修改原型
void checkBelowZero(float *x);
并像這樣呼叫函式
checkBelowZero(&largerBase);
這確保傳遞我們變數的基地址。
解決方案 2
由于您正在回傳值x,因此您實際上可以將值設定為largerBase函式的回傳值。
largerBase = checkBelowZero(largerBase);
請記住,x不需要定義為變數。因為它是一個只有它所屬的函式才能訪問的引數
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/451548.html
