gpt4 book ai didi

c++ - 我一直在尝试用 C++ 编写一个程序,使用类和对象将华氏度转换为摄氏度,反之亦然

转载 作者:太空宇宙 更新时间:2023-11-04 11:42:04 24 4
gpt4 key购买 nike

我只是想指出我是新手,所以如果我做错了什么,我很抱歉。我也是 c++ 的新手。我以前用 c 编程过,所以我唯一真正遇到麻烦的是面向对象编程。我正在尝试将其应用于程序。我知道如何使用函数和 switch 语句来编写这个程序,但我正在尝试将面向对象的编程应用到这个程序的想法中。

我想使用 float 类型,以便可以输入和打印小数,但我可以使用 integers

当我运行该程序时,我得到了非常大的数字,这些数字没有意义。这些数字永远不会相同。对不起,我没有评论:

#include <iostream>
#include <conio.h>

using namespace std;

class Celsius{
public:
float setValue(float c){
value = c;
}
float changeValue(float value){
returnValue = value * 9 / 5 + 32;
}
float getValue(){
return returnValue;
}
private:
float value;
float returnValue;
};

class Fahrenheit{
public:
float setValue(float f){
value = f;
}
float changeValue(float value){
returnValue = (value - 32)*5/9;
cout << returnValue;
}
float getValue(){
return returnValue;
}
private:
float value;
float returnValue;
};


int main()
{
char type;
float value1;

cout << "Do have a celsius or fahrenheit degree? (Press c for celsius and f for fahrenheit.) ";
cin >> type;
cout << "Enter a temperature value: ";
cin >> value1;

if(type == 'C' || type == 'c'){
Celsius metricObject;
metricObject.setValue(value1);
cout << "In Fahrenheit, that is: " << metricObject.getValue();
}
else if(type == 'F' || type == 'f'){
Fahrenheit englishObject;
englishObject.setValue(value1);
cout << "In celsius, that is: " << englishObject.getValue();

}
else{
return(0);
}
return(0);
}

最佳答案

您缺少对摄氏度和华氏度的 changeValue() 调用。

在调用 getValue() 之前,先对 metricObject 和 englishObject 调用 changeValue()。这应该给出一些合理的值。

关于c++ - 我一直在尝试用 C++ 编写一个程序,使用类和对象将华氏度转换为摄氏度,反之亦然,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21011186/

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