Celcius 如果(c==1){ cout>fah; cel=(5/9)*(fah-32); cout,c++,C++" /> Celcius 如果(c==1){ cout>fah; cel=(5/9)*(fah-32); cout,c++,C++" />

很难得到否定的答案 嘿,伙计们,我对C++是全新的,而且我遇到了一个问题,那就是把一个方程变成华氏度到摄氏度。p> // Fahrenheit -> Celcius if (c==1) { cout << "\nPlease give the temperature in degrees Fahrenheit: "; cin >> fah; cel=(5/9)*(fah-32); cout << "\n" << fah << " degrees Fahrenheit corresponds to " << cel << " degrees Celcius."; } //Fahrenheit->Celcius 如果(c==1){ cout>fah; cel=(5/9)*(fah-32); cout

很难得到否定的答案 嘿,伙计们,我对C++是全新的,而且我遇到了一个问题,那就是把一个方程变成华氏度到摄氏度。p> // Fahrenheit -> Celcius if (c==1) { cout << "\nPlease give the temperature in degrees Fahrenheit: "; cin >> fah; cel=(5/9)*(fah-32); cout << "\n" << fah << " degrees Fahrenheit corresponds to " << cel << " degrees Celcius."; } //Fahrenheit->Celcius 如果(c==1){ cout>fah; cel=(5/9)*(fah-32); cout,c++,C++,5/9是整数算术,因此等于0 尝试(5.0/9)来鼓励编译器使用浮点。或者,使用(5.f/9)问题是您无意中转换为整数,因此分数将被截断 建议更改: if (c==1) { cout << "\nPlease give the temperature in degrees Fahrenheit: "; cin >> fah; cel=(5.0/9.0)*(fah-32.0); cout << "\n" << fah

5/9
是整数算术,因此等于0


尝试
(5.0/9)
来鼓励编译器使用浮点。或者,使用
(5.f/9)

问题是您无意中转换为整数,因此分数将被截断

建议更改:

if (c==1) {
    cout << "\nPlease give the temperature in degrees Fahrenheit: ";
    cin >> fah;
    cel=(5.0/9.0)*(fah-32.0);
    cout << "\n" << fah << " degrees Fahrenheit corresponds to " << cel << " degrees Celcius.";
}
if(c==1){
cout>fah;
cel=(5.0/9.0)*(fah-32.0);

cout尝试使用double而不是int来获得好的十进制结果,不是每个转换都是一对一的

编辑:试着把你的5/9改成十进制,但是,把这段代码复制过来作为参考。我把你的变量“C”设为1,这样我就不必太多地修改你原来的代码了。这些不是最普遍接受的编码方法,但它回答了你的问题

// test.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
double c=1;
double fah=0;
double cel=0;

// Fahrenheit -> Celcius
if (c==1) {
cout << "\nPlease give the temperature in degrees Fahrenheit: ";

cin >> fah;

cel=(.5556)*(fah-32);

cout << setprecision(3)<<"\n" << fah << " degrees Fahrenheit corresponds to " << cel << "    degrees Celcius.";
}//endif
system ("pause");
return 0;

}
//test.cpp:定义控制台应用程序的入口点。
//
#包括“stdafx.h”
#包括
#包括
使用名称空间std;
int main()
{
双c=1;
双fah=0;
双细胞=0;
//华氏->摄氏度
如果(c==1){
cout>fah;
cel=(.5556)*(fah-32);

cout您还可以为浮点操作键入cast(5/9)。它可以写成((float)5/9)。这应该可以解决您的问题。

详细检查这段代码的每一部分。当您应该使用浮点时,不要使用整数算术。@DavidHammen编译器会对整数除法发出警告吗?我觉得他们应该=/@Nabla OP只是注意到它在这种情况下失败了-对于所有不是32.I的F值,转换都是错误的怀疑
fah
是浮点/双so
(0*anyFiniteNegativeFloat)->-0f
@Borgleader他们为什么要这样做?这是一个有效的操作,引入警告只会在您实际打算进行整数除法时发出虚假的警告。
5f
不是浮点文字-。小数点是必需的-
5.f
@Angew-谢谢,我以为我把它放错了,没有注意到直到后来你编辑了我的评论。我将把它放回原处。我是C程序员,设法跳过C++。我错误地认为这个语法没有改变。有倒退:- BTW,更喜欢在除法之前执行乘法:5 *(FAH - 32)/9.0.这有助于减少浮点误差。
int
什么时候不允许出现负结果?你完全正确,我更喜欢对十进制结果使用双精度将编辑答案使用
float
对此没有问题……除非他真的需要超过5位小数的精度(可疑)我想,既然他是C++的新手,我就想看如何处理小数。我的答案是从一个几乎和他差不多的人的角度来看。因为这是他当前代码中的一个文字,这是最不喜欢的方法。如果你处理一个文字,并期望它是某种类型的,那么声明该类型的文本…不要转换它。