我正在使用此代码来计算输入的平方和立方体,并且我添加了第三个选项来计算值除以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