gpt4 book ai didi

c - C中的函数通信

转载 作者:太空宇宙 更新时间:2023-11-04 01:23:36 25 4
gpt4 key购买 nike

我的函数通讯有问题。我向用户询问摄氏温度,它以华氏温度返回。完美!问题是之后用户输入的华氏度不会给我摄氏度。相反,它采用华氏度的先前值并将其发送到方程式“5 *(华氏度 - 32)/9”。所以从技术上讲,我得到了两个结果。合理? 谢谢。

#include <stdio.h>
#include <stdlib.h>

//prototypes
float get_c (float *celsius);
float get_f (float *fahrenheit);
float cel_to_fah (float celsius);
float fah_to_cel (float fahrenheit);
float display_F (float celsius, float fahrenheit);
float display_C (float fahrenheit, float celsius);

int main (void)
{
//variable declaration
float celsius = 0; //stores degree Celsius
float fahrenheit = 0; //stores degree Fahrenheit

//function calls
get_c (&celsius);
get_f (&fahrenheit);
//===============================
fahrenheit = cel_to_fah (celsius);
celsius = fah_to_cel (fahrenheit);
//===============================
display_F (celsius, fahrenheit);
display_C (fahrenheit, celsius);

return 0;
}
//===================================================================
float get_c (float *celsius)
{
printf("Please enter a degree Celsius: ");
scanf("%f", celsius);

return 0;
}//get_c

float get_f (float *fahrenheit)
{
printf("Please enter a degree Fahrenheit: ");
scanf("%f", fahrenheit);

return 0;
}//get_f

//===================================================================
float cel_to_fah (float celsius)
{
return (1.8 * celsius) + 32;
}//cel_to_fah

float fah_to_cel (float fahrenheit)
{
return 5 * (fahrenheit - 32) / 9;
}//fah_to_cel

//===================================================================
float display_F (float celsius, float fahrenheit)
{
printf("====================================\n");
printf("%.2f Celsius in Fahrenheit is: %.2f\n", celsius, fahrenheit);
return fahrenheit;
}//display_F

float display_C (float fahrenheit, float celsius)
{
printf("====================================\n");
printf("%.2f Fahrenheit in Celsius is: %.2f\n", fahrenheit, celsius);
printf("====================================\n");
return celsius;
}//display_C

最佳答案

您应该将转换后的结果存储到其他变量中,以免破坏用户输入。

试试这个:

int main (void)
{
//variable declaration
float celsius = 0; //stores degree Celsius
float fahrenheit = 0; //stores degree Fahrenheit
float celsius_converted = 0; //stores degree Celsius converted
float fahrenheit_converted = 0; //stores degree Fahrenheit converted

//function calls
get_c (&celsius);
get_f (&fahrenheit);
//===============================
fahrenheit_converted = cel_to_fah (celsius);
celsius_converted = fah_to_cel (fahrenheit);
//===============================
display_F (celsius, fahrenheit_converted);
display_C (fahrenheit, celsius_converted);

return 0;
}

关于c - C中的函数通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36001495/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com