我试过从命令行执行这个算术表达式,但它没有给我有效的输出。如何使用最简单的C ++技能在下面的代码中执行表达式?
#include <iostream>
using namespace std;
int main()
{
cout << " 4 * (1.0 - 1/3 + 1/5 - 1/7 + 1/9 - 1/11) = ";
return 0;
}
答案 0 :(得分:3)
第一个问题是你实际上没有进行任何计算,你只是将文字方程打印成一串字符。您将面临的第二个问题是1/3
是整数1除以整数3.整数除法不考虑小数。添加小数点以将整数文字转换为双精度。
#include <iostream>
using namespace std;
int main()
{
// Prints the equation
cout << " 4 * (1.0 - 1./3 + 1./5 - 1./7 + 1./9 - 1./11) = ";
// Prints the result of the equation
cout << 4 * (1.0 - 1./3 + 1./5 - 1./7 + 1./9 - 1./11);
return 0;
}
答案 1 :(得分:3)
最好使用浮点数据类型(例如double
:
#include <iostream>
#include <cstdlib>
int main(void)
{
double pi = 4.0 * (1.0 - 1.0/3.0 + 1.0/5.0 - 1.0/7.0 + 1.0/9.0 - 1.0/11.0);
std:: cout << "PI: " << pi << "\n";
return EXIT_SUCCESS;
}
简而言之,cout
工具不评估文本字符串,只输出它们。