创建一个将Centigrade转换为Wahrenheit的课程,反之亦然
Creating a Class to convert Centigrade to Fahrenheit and vice versa
我最近在我的高中课程中开始在C 上编程。我目前正在学习课程,并且我遇到了一些麻烦,可以创建一门课程,该课程将从Centigrade转换为华氏和华氏度,再到Centigrade。我觉得我完全做错了。任何帮助都会很棒。该程序运行良好,但不转换,我该如何抓住" dcent"answers" dfahr"并在转换类中使用它?
#include <iostream>
using namespace std;
int main() {
int nUserInput;
double dCent, dFahr;
cout << "Do you want to convert from Centigrade to Fahrenheit [1] or from Fahrenheit to Centigrade [2]" <<endl;
cin >> nUserInput;
if (nUserInput == 1) {
cout << "Enter the Centigrade" <<endl;
cin >> dCent;
} else if (nUserInput == 2) {
cout << "Enter the Fahrenheit" <<endl;
cin >> dFahr;
}
Convert tempConverter;
tempConverter.
}
class Convert {
public:
void centToFahr() {
//dCent = dCent * 9 / 5 + 32;
}
void fahrToCent() {
//dCent = (dFahr - 32) * 5 / 9;
}
};
尝试以下:
class Convert {
public:
double centToFahr(double dCent) {
return dCent * 9 / 5 + 32;
}
double fahrToCent(double dFahr) {
return (dFahr - 32) * 5 / 9;
}
};
int main() {
int nUserInput;
double dCent, dFahr;
Convert tempConverter;
cout << "Do you want to convert from Centigrade to Fahrenheit [1] or from Fahrenheit to Centigrade [2]" << endl;
cin >> nUserInput;
if (nUserInput == 1) {
cout << "Enter the Centigrade" << endl;
cin >> dCent;
cout << "dFahr = " << tempConverter.centToFahr(dCent);
}
else if (nUserInput == 2) {
cout << "Enter the Fahrenheit" << endl;
cin >> dFahr;
cout << "dCent = " << tempConverter.fahrToCent(dFahr);
}
}
我遇到了一些麻烦,可以创建一堂课,该课程将从摄氏(Centigrade)转变为华氏和华氏(Wahrenheit),再到Centigrade。
选项1
- 您可以将温度存储为成员变量。
- 更改函数以返回值,而不是使用
void
返回类型。
class Convert
{
public:
Convert(double val) : val_(val) {}
double centToFahr() {
return (val_* 9 / 5 + 32);
}
double fahrToCent() {
return (val_ - 32) * 5 / 9
}
private:
double val_;
};
选项2
选项1 中的解决方案遇到了Convert
不知道其存储的值是Centigrade还是在华氏度中的问题。如果您致电centToFahr
,则将该值视为摄氏。如果您致电fahrToCent
,则该值将在华氏度。
您最好完全没有成员变量,并期望温度值作为参数。
class Convert
{
public:
// OK to assume val to be in Centigrade
double centToFahr(double val) {
return (val * 9 / 5 + 32);
}
// OK to assume val to be in Fahrenheit
double fahrToCent(double val) {
return (val - 32) * 5 / 9
}
};
相关文章:
- 在C++中,是否可以基于给定的标识符创建基类的新实例,反之亦然
- 在C++中,将int值赋给enum,反之亦然
- 如何在 c++ 中将所有大写字母转换为字符串中的小写字母,反之亦然?
- 将通用引用强制转换为可调用的 void 指针,反之亦然
- 用非原子更新原子变量,反之亦然
- 从向量到空指针的 memcpy(反之亦然)不起作用
- 将基类分配给派生对象,反之亦然,以C++以及静态和动态对象之间的差异
- 如何在 OpenCL 中将小写转换为大写,反之亦然
- 如何将CNG密钥转换为OpenSSL EVP_PKEY(反之亦然)?
- C++ - 使用结构数据类型将单词中的单个小写字符更改为大写,反之亦然
- 快速将无符号字符的向量强制转换为POD结构的向量,反之亦然
- 在C++中,将无符号整数转换为八进制表示,反之亦然的最佳方法是什么
- 使用C++将越南语字符从ISO88591、UTF8、UTF16BE、UTF16LE和UTF16编码为十六进制,反之亦然
- AVX2 SIMD Instrinsics 16 位到 8 位,反之亦然
- 将 char[] 数组转换为字节,然后将字节转换为 int,反之亦然
- 将字节数组 (uint8_t) 转换为单词数组 (uint16_t),反之亦然
- 在Qt中将QString转换为ASCII值,反之亦然
- 封送处理 - 转换 std::向量<char>到字符串^ 反之亦然
- C++阿拉伯数字到罗马数字,反之亦然
- 创建一个将Centigrade转换为Wahrenheit的课程,反之亦然