我必须编写一个程序,要求用户输入重量和行星名称。程序必须输出用户在那个星球上的体重。出于某种原因,我得到错误:“'=':从'double'到'int'的转换,可能会丢失数据。
在我尝试使用 (planet == Mercury) 但仍然没有运气之前。
这是我的代码:
// ConsoleApplication5.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
#include "ConsoleApplication5.h"
using namespace std;
int main()
{
cout << "Assignment 05" << endl;
int weight = 0;
string planet = "";
int weightOnplanet;
string entry = "You entered a weight of ";
string Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus, Neptune, Pluto;
cout << "Please Enter Weight <as an integer of pounds>: " << endl;
cin >> weight;
cout << "Please Enter Planet name <ie: Earth>: " << endl;
cin >> planet;
cout << entry << weight << " and a planet name of " + planet << endl;
if (planet == Mercury)
{
weightOnplanet = weight * 0.4155;
cout << "On a " + planet + " your weight in pounds would be " << weightOnplanet << endl;
}
else if (planet == Venus)
{
weightOnplanet = weight * 0.8975;
cout << "On a " + planet + " your weight in pounds would be " << weightOnplanet << endl;
}
else if (planet == Earth)
{
weightOnplanet = weight * 1.0;
cout << "On a " + planet + " your weight in pounds would be " << weightOnplanet << endl;
}
else if (planet == Mars)
{
weightOnplanet = weight * 0.3507;
cout << "On a " + planet + " your weight in pounds would be " << weightOnplanet << endl;
}
else if (planet == Jupiter)
{
weightOnplanet = weight * 2.5374;
cout << "On a " + planet + " your weight in pounds would be " << weightOnplanet << endl;
}
else if (planet == Saturn)
{
weightOnplanet = weight * 1.0677;
cout << "On a " + planet + " your weight in pounds would be " << weightOnplanet << endl;
}
else if (planet == Uranus)
{
weightOnplanet = weight * 0.8947;
cout << "On a " + planet + " your weight in pounds would be " << weightOnplanet << endl;
}
else if (planet == Neptune)
{
weightOnplanet = weight * 1.1794;
cout << "On a " + planet + " your weight in pounds would be " << weightOnplanet << endl;
}
else if (planet == Pluto)
{
weightOnplanet = weight * 0.0899;
cout << "On a " + planet + " your weight in pounds would be " << weightOnplanet << endl;
}
else
cout << "Unknown Planet" << endl;
system("pause");
return 0;
}
最佳答案
每个行星变量(水星、金星等)都应该有一个实际值,例如:
Mercury = "Mercury";
字符串不会用变量名初始化,你必须实际给它一个值。
您甚至不必为每个行星都设置一个变量。你可以这样做:
if(planet == "Mercury")
关于C++ 将输入字符串与字符串进行比较会警告我从 double 到 int 的转换 - 可能会丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48820250/