我正在使用此代碼來計算輸入的平方和立方體,並且我添加了第三個選項來計算值除以2,所以我不得不將結果從int修改爲double,但我認爲我沒有做到這一點。這是我到目前爲止:如何在此while循環中將int更改爲double,C
#include <stdio.h>
// Function prototypes int Square(int value); int Cube(int value);
int main()
{
/* variable definition: */
int intValue, menuSelect,Results;
double doubleValue, Resultsb;
intValue = 1;
doubleValue = intValue;
// While a positive number
while (intValue > 0) {
printf ("Enter a positive Integer\n: ");
scanf("%d", &intValue);
doubleValue=intValue;
if (intValue > 0) {
printf ("Enter 1 to calculate Square, 2 to Calculate Cube, 3 to Shrink
value in half \n: ");
scanf("%d", &menuSelect);
if (menuSelect == 1) {
// Call the Square Function
Results = Square(intValue);
printf("Square of %d is %d\n",intValue,Results);
}
else if (menuSelect == 2) {
// Call the Cube function
Results = Cube(intValue);
printf("Cube of %d is %d\n",intValue,Results);
}
else if (menuSelect == 3) {
Resultsb = Shrink(doubleValue);
printf("%f shrunk in half is %f\n", doubleValue,Resultsb);
}
else
printf("Invalid menu item, only 1, 2 or 3 is accepted\n");
}
}
return 0;
}
/* function returning the Square of a number */
int Square(int value)
{
return value*value;
}
/* function returning the Cube of a number */
int Cube(int value)
{ return value*value*value;
}
double Shrink(double value)
{ return value/2;
}
如果有人能告訴我我做錯了什麼,那將是驚人的,謝謝!
您不需要將輸入轉換爲雙精度型。當你調用'Shrink()'時,它會自動轉換,因爲參數是雙精度。 – Barmar
爲什麼你將原型註釋掉了?你還需要一個'Shrink()'的原型。 – Barmar
您需要在'main()'之前''Shrink()''的聲明(aka prototype)。否則,你的程序的行爲是未定義的(C的早期版本,因爲編譯器會在調用點假定'Shrink()'返回'int'並相應地處理它)或不會編譯(最新版本的C)。 – Peter