我使用return命令然后尝试从main打印值。它返回零(0)的值。
该程序是关于从摄氏温度到华氏温度的温度转换。
另外,如何使用舍入函数将答案舍入为整数,使其不是带小数的浮点数。
#include <stdio.h>
int Cel_To_Fah(int a, int b); // function declaration
int main (void)
{
int a;
int b;
printf(" Enter temperatrure: "); scanf("%d", &a);
Cel_To_Fah(a,b); // function call
printf("The temperature is: %d\n", b);
return 0;
} // main
int Cel_To_Fah(a,b)
{
b=1.8*a+32;
return b;
} // Cel_To_Fah
答案 0 :(得分:6)
您只需使用赋值运算符:
b = Cel_To_Fah(a);
但是,您的程序存在很多问题,包括您的Cel_To_Fah
函数没有正确的签名。你可能想要这样的东西:
int Cel_To_Fah(int a)
{
return 1.8 * a + 32;
}
你应该得到一本好的初学C书。
答案 1 :(得分:1)
不需要函数(b)的第二个参数。
你可以通过......
来做到这一点 #include<stdio.h>
int Cel_To_Fah(int a); // function declaration, as it returns a values;
int main (void)
{
int a; int b;
printf(" Enter temperatrure: ");
scanf("%d", &a);
b = Cel_To_Fah(a); /* the returned value is stored into b, and as b is an integer so it is automatically rounded. no fraction point value can be stored into an integer*/
printf("The temperature is: %d\n", b);
return 0;
} // main
int Cel_To_Fah(int a)
{
return 1.8 * a + 32;
}
答案 2 :(得分:1)
有几个问题。首先,您需要使用float,而不是int,以便您可以使用带小数点的值。否则你的计算会出错。出于同样的原因,也使用32.0而不是32。
其次,您需要了解函数中的a和b与main中的a和b不同。它们具有相同的名称,但不在同一“范围”中。因此,更改函数中的那个不会影响main中的那个。这就是为什么在主要你必须说b = Cel ...所以b中的b将获得返回值。
最后,在c中,你应该把你的功能放在主要之前/之前。否则它在技术上尚未定义“尚未”,尽管一些现代编译器会为您解决这个问题。阅读有关函数原型的信息。
答案 3 :(得分:0)
由于函数Cel_To_Fah(a,b);
返回值(int
类型),因此必须将其分配给其返回类型(int
类型)的变量。
int a;
int b;
printf(" Enter temperatrure: "); scanf("%d", &a);
b = Cel_To_Fah(a); // function call
printf("The temperature is: %d\n", b);
,你的功能应该是
int Cel_To_Fah(a)
{
int b = 1.8*a+32;
return b;
} // Cel_To_Fah
不要忘记将您的函数原型更改为
int Cel_To_Fah(int a);
答案 4 :(得分:0)
我在你的代码中看到了两个问题。首先,它是变量类型。我假设你想要摄氏度为整数;但是华氏度= 1.8 *摄氏度+ 32应该是浮动的。因此b应该是浮动的。
其次,您不应该通过其输入参数从函数返回值(除非您通过ref学习指针或调用)。我重写你的代码如下:
include<stdio.h>
float Cel_To_Fah(int a); // function declaration
int main (void)
{
int a;
float b;
printf(" Enter temperatrure: "); scanf("%d", &a);
b=Cel_To_Fah(a); // function call
printf("The temperature is: %.2f\n", b); //showing 2 decimal places
return 0;
} // main
float Cel_To_Fah(int a)
{
float b;
b=1.8*(float)a+32; //cast a from int to float
return b;
} // Cel_To_Fah