C++:为什么我必须以这种方式将我的声明命令为 double?

C++: Why must I order my declaration as a double in this manner?

所以我的任务之一是制作一个转换货币的程序,下面这个程序转换 U.S。美元兑某些南美元。

我不确定为什么我不能将美元变量与其他货币变量一起声明。我是这样做的,程序搞砸了转换:

double dollars;

double pesos = dollars * 26;

double reais = dollars * 5.9;

double soles = dollars * 3.53;

std::cout << "Enter the number of U.S. dollars you have:";
std::cin >> dollars;

std::cout << "In colombian pesos, that's " << pesos << "\n";
std::cout << "In brazilean reals, that's " << reais << "\n";
std::cout << "In peruvian soles, that's " << soles << "\n";

input/output 是这样的:

Enter the number of U.S. dollars you have:1
In colombian pesos, that's 0
In brazilean reals, that's 0
In peruvian soles, that's 0

然而,当我运行这样的代码时(将输入直接放在dollars的声明之后),输入执行正确的转换:

double dollars;

std::cout << "Enter the number of U.S. dollars you have:";
std::cin >> dollars;

double pesos = dollars * 26;

double reais = dollars * 5.9;

double soles = dollars * 3.53;

std::cout << "In colombian pesos, that's " << pesos << "\n";
std::cout << "In brazilean reals, that's " << reais << "\n";
std::cout << "In peruvian soles, that's " << soles << "\n";

我认为变量声明放在哪里并不重要,只要我在使用它之前声明它即可。

声明中的表达式立即计算

以下语句初始化 变量 使用立即用 dollars 计算的表达式,因为它在那个确切时刻 是已知的:

double pesos = dollars * 26;
double reais = dollars * 5.9;
double soles = dollars * 3.53;

它不像 Excel 会根据最新已知值重新计算的公式。这就是为什么:

  • 在第一种情况下,计算是在用户输入之前进行的。您可能会看到奇怪的结果,因为 dollars 尚未初始化。顺便说一句,最好初始化你声明的变量。

  • 在第二种情况下,计算是在用户输入 dollars 之后进行的,因此会提供您期望的结果。

函数可以在你需要的时候计算表达式

如果你想定义一个通用公式来进行计算而不立即进行计算,你应该定义functions:

double pesos(double dollars) {return dollars * 26;}
double reais(double dollars) {return  dollars * 5.9;}
double soles(double dollars) {return  dollars * 3.53;}

这些函数中的每一个都使用一个表达式,该表达式将在调用函数时进行计算。计算将使用作为参数传递的 dollar 值。例如:

std::cout << "In mexican pesos, that's " << pesos(dollars) << "\n";
std::cout << "In brazilean reals, that's " << reais(dollars) << "\n";
std::cout << "In peruvian soles, that's " << soles(dollars) << "\n";

您可以多次调用同一函数,以始终根据提供的参数进行 up-to-date 计算:

std::cout << "3.14 dollars in brazilean reals is " << reais(3.14) << "\n";
std::cout << "500/3 dollars in brazilean reals is " << reais(500.0/3.0) << "\n";
double another_value=0.0;  
std::cin >> another_value; 
std::cout << another_value << "dollars in brazilean reals is " << reais(another_value) << std::endl;