简体   繁体   English

无法得到否定答案

[英]Having trouble getting a negative answer

Hey guys I'm brand new to C++ and I'm having trouble with an equation to change degrees Fahrenheit to degrees Celsius. 嘿伙计们我是C ++的新手,我在用一个等式来改变华氏度到摄氏度时遇到了麻烦。

// 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.";
}

When I put in a value for fah below 32, my answer in degrees celcius comes back as -0. 当我输入低于32的fah值时,我的度数为celcius的回答为-0。 How can I get a value below 0 for my answer? 如何获得低于0的值作为答案? Btw I used float for all of my variables. 顺便说一下,我使用浮点数来表示所有变量。

5/9 is integer arithmetic and, therefore, equals 0. 5/9是整数运算,因此等于0。

Try (5.0/9) instead to encourage the compiler to use floating point. 尝试(5.0/9)而不是鼓励编译器使用浮点。 Alternatively, use (5.f/9) . 或者,使用(5.f/9)

The problem is that you're inadvertantly converting to integer - so your fractions will get truncated. 问题是你无意中转换为整数 - 所以你的分数会被截断。

SUGGESTED CHANGE: 建议更改:

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.";
}

Try using double instead of int to allow good decimal results not every conversion is one for one 尝试使用double而不是int来允许良好的十进制结果,而不是每次转换都是一对一的

edit: Try changing your 5/9 to a decimal but, copy this code over for referance I set your variable "C" to 1 just so I didnt have to change your original code too much. 编辑:尝试将您的5/9更改为小数,但是,将此代码复制到referance我将您的变量“C”设置为1,这样我就不必更改原始代码了。 These arent the most accepted coding practices but its an answer to your question. 这些不是最受欢迎的编码实践,但它是您的问题的答案。

// 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;

}

You could also type-cast (5/9) to a float operation. 你也可以输入(5/9)到float操作。 It can be written as ((float)5/9). 它可以写成((float)5/9)。 That should solve your problem. 那应该可以解决你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM