Может кто-нибудь помочь мне понять, почему это дает результат 0?
#include <iostream>
using namespace std;
int main() {
float celsius;
float fahrenheit;
cout << "Enter Celsius temperature: ";
cin >> celsius;
fahrenheit = (5/9) * (celsius + 32);
cout << "Fahrenheit = " << fahrenheit << endl;
return 0;
}
Ответ 1
(5/9)
будет по умолчанию вычисляться как целочисленное деление и будет равен нулю. Попробуйте (5.0/9)
Ответ 2
Фаренгейт к Цельсию был бы (Fahrenheit - 32) * 5 / 9
Ответ 3
В С++ 5/9 вычисляет результат как целое число, так как оба операнда являются целыми числами. Вам нужно дать подсказку компилятору, что вы хотите получить результат как float/double. Вы можете сделать это, явно бросая один из операндов вроде ((double)5)/9;
ИЗМЕНИТЬ
Поскольку он помечен С++, вы можете сделать бит отливки более элегантно, используя static_cast
. Например: static_cast<double>(5)/9
. Хотя в этом конкретном случае вы можете напрямую использовать 5.0/9 для получения желаемого результата, кастинг будет полезен, если у вас есть переменные вместо постоянных значений, таких как 5.
Ответ 4
В примере кода вы пытаетесь разделить целое число с другим целым числом. Это причина всех ваших проблем. Вот статья которая может оказаться интересной по этому вопросу.
С понятием целочисленного деления вы сразу видите, что это не то, что вы хотите в своей формуле. Вместо этого вам нужно использовать литералы с плавающей запятой.
Я довольно смущен заголовком этого потока и вашего образца кода. Вы хотите преобразовать градусы Цельсия в Фаренгейт или сделать наоборот?
Я опишу свой пример кода на свой собственный образец кода, пока вы не дадите более подробную информацию о том, что вы хотите.
Вот пример того, что вы можете сделать:
#include <iostream>
//no need to use the whole std namespace... use what you need :)
using std::cout;
using std::cin;
using std::endl;
int main()
{
//Variables
float celsius, //represents the temperature in Celsius degrees
fahrenheit; //represents the converted temperature in Fahrenheit degrees
//Ask for the temperature in Celsius degrees
cout << "Enter Celsius temperature: ";
cin >> celsius;
//Formula to convert degrees in Celsius to Fahrenheit degrees
//Important note: floating point literals need to have the '.0'!
fahrenheit = celsius * 9.0/5.0 + 32.0;
//Print the converted temperature to the console
cout << "Fahrenheit = " << fahrenheit << endl;
}
Ответ 5
Лучший способ -
#include <iostream>
using namespace std;
int main() {
float celsius;
float fahrenheit;
cout << "Enter Celsius temperature: ";
cin >> celsius;
fahrenheit = (celsius * 1.8) + 32;// removing division for the confusion
cout << "Fahrenheit = " << fahrenheit << endl;
return 0;
}
:)
Ответ 6
Мина отлично работала!
/* Two common temperature scales are Fahrenheit and Celsius.
** The boiling point of water is 212° F, and 100° C.
** The freezing point of water is 32° F, and 0° C.
** Assuming that the relationship bewtween these two
** temperature scales is: F = 9/5C+32,
** Celsius = (f-32) * 5/9.
***********************/
#include <iostream> // cin, cout
using namespace std; // System definition of cin and cout commands,
// if not, programmer would have to write every
// single line as: std::cout or std::cin
int main () // Main function
{
/* Declare variables */
double c, f;
cout << "\nProgram that changes temperature from Celsius to Fahrenheit.\n";
cout << "Please enter a temperature in Celsius: ";
cin >> c;
f = c * 9 / 5 + 32;
cout << "\nA temperature of " << c << "° Celsius, is equivalent to "
<< f << "° Fahrenheit.\n";
return 0;
}
Ответ 7
Ответ уже найден, хотя я также хотел бы поделиться своим ответом:
int main(void)
{
using namespace std;
short tempC;
cout << "Please enter a Celsius value: ";
cin >> tempC;
double tempF = convert(tempC);
cout << tempC << " degrees Celsius is " << tempF << " degrees Fahrenheit." << endl;
cin.get();
cin.get();
return 0;
}
int convert(short nT)
{
return nT * 1.8 + 32;
}
Это более правильный способ сделать это; однако, это немного сложнее, чем то, что вы делали.
Ответ 8
Это самый простой, который я мог бы придумать, поэтому хотел поделиться здесь,
#include<iostream.h>
#include<conio.h>
void main()
{
//clear the screen.
clrscr();
//declare variable type float
float cel, fah;
//Input the Temperature in given unit save them in ‘cel’
cout<<"Enter the Temperature in Celsius"<<endl;
cin>>cel;
//convert and save it in ‘fah’
fah=1.8*cel+32.0;
//show the output ‘fah’
cout<<"Temperature in Fahrenheit is "<<fah;
//get character
getch();
}
Источник: Цельсия до Фаренгейта