我正在使用这段代码计算输入的平方和立方,我添加了第三个选项来计算除以2的值,所以我不得不将结果从int改为double,但我认为我做得不对以下是我目前掌握的情况:
#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;
}
如果有人能告诉我我做错了什么,那就太棒了,谢谢!
最佳答案
在调用函数之前,需要该函数的原型否则,默认返回类型为int
所以说:
int Square(int value);
int Cube(int value);
double Shrink(double value);
在
main()
之前,或将函数定义移到顶部。您也不需要
doubleValue
变量将intValue
传递给函数将根据原型自动转换它。这是工作程序。
#include <stdio.h>
// Function prototypes
int Square(int value);
int Cube(int value);
double Shrink(double value);
int main ()
{
/* variable definition: */
int intValue, menuSelect,Results;
double Resultsb;
intValue = 1;
// While a positive number
while (intValue > 0) {
printf ("Enter a positive Integer\n: ");
scanf("%d", &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(intValue);
printf("%d shrunk in half is %f\n", intValue,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;
}