【问题标题】:Can't find out why my display value is always 0找不到为什么我的显示值总是0
【发布时间】:2017-10-18 12:29:36
【问题描述】:

Kelvin 到 C 或 F 的转换程序,它使用我们实验室的函数。我不知道为什么我一直得到 0 作为输出。我认为这与我传递/返回值的方式有关。我可能还没有得到回报?

#include <stdio.h>
#include <ctype.h>


float KtoC(float kel)
{
    kel = - 273;

    return(kel);
}

float KtoF(float kel)
{
    kel = (9 * kel / 5) + 32;

    return(kel);
}

float GetKelvin(float kel)
{
    printf("Temperature Conversion Program\n");
    printf("Please enter a temperature in Degrees Kelvin:");
    scanf("%f%*c", &kel);

    return(kel);
}

char GetConvType(char &ctype)
{
    do
        {
        printf("Convert to Celcius (c) or Fahrenheit (f): ");
        scanf("%c%*c", &ctype);

        ctype = tolower(ctype);

        } while(ctype != 'c' && ctype != 'f');

    return(ctype);
}

float GetConvTemp(float kel)
{
    char ctype;

    ctype = GetConvType(ctype);

    if(ctype == 'c')
    {
        return (KtoC(kel));
    }
    else
    {
        return (KtoF(kel));
    }
}   

void DisplayResults(float x)
{
    printf("This is the temp converted %f", x);

    return;
}



int main()
{
    float kel, x;
    char ctype;

    GetKelvin(kel);
    GetConvType(ctype);
    GetConvTemp(kel);
    DisplayResults(kel);

    return(0);

}

【问题讨论】:

  • 因为你没有使用GetKelvin(kel);的返回值
  • 多么奇怪的程序编写方式
  • 请注意,char GetConvType(char &amp;ctype) 是 C++,而不是 C。
  • @FedericoklezCulloca 是的,我知道...很久没干了,我们从 C 开始。
  • 顺便说一下,KtoC 总是返回 -273。您应该使用kel -= 273 而不是kel = -273

标签: c++ parameter-passing return-value modular


【解决方案1】:
--- xorg.cpp    2017-05-19 00:48:56.000000000 +0900
+++ x.cpp   2017-05-19 00:50:23.000000000 +0900
@@ -4,19 +4,19 @@

 float KtoC(float kel)
 {
-   kel = - 273;
+   kel -= 273.0;

    return(kel);
 }

 float KtoF(float kel)
 {
-   kel = (9 * kel / 5) + 32;
+   kel = (9.0 * KtoC(kel) / 5.0) + 32.0;

    return(kel);
 }

-float GetKelvin(float kel)
+float GetKelvin(float &kel)
 {
    printf("Temperature Conversion Program\n");
    printf("Please enter a temperature in Degrees Kelvin:");
@@ -39,7 +39,7 @@
    return(ctype);
 }

-float GetConvTemp(float kel)
+float GetConvTemp(float &kel)
 {
    char ctype;

@@ -71,8 +71,7 @@

    GetKelvin(kel);
    GetConvType(ctype);
-   GetConvTemp(kel);
-   DisplayResults(kel);
+   DisplayResults(GetConvTemp(kel));

    return(0);

【讨论】:

  • 这个问题需要错误的解释,而不仅仅是工作代码的差异。请edit 解释原始版本有什么问题,以及为什么这些更改会有所帮助。
猜你喜欢
  • 2011-12-27
  • 1970-01-01
  • 2021-04-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-25
相关资源
最近更新 更多