[英]C++ std:cout won't print, despite me using std::endl to enter newline and flush
I'm new to C++ (and mainly programming in general).我是 C++ 的新手(主要是一般的编程)。
I'm trying to write a basic program to output the Taylor expansion of x = 1.5 from n = 1 to n = 100. My code is this:我正在尝试编写一个基本程序来输出 x = 1.5 从 n = 1 到 n = 100 的泰勒展开式。我的代码是这样的:
#include <iostream>
int main() {
double x = 1.5;
double expx = 1;
double summand = 1;
for (int n=1; n <100; ++n) {
summand *= x/n;
expx += summand;
}
return expx
std::cout << "final expx from n = 1 to 100 is " << expx << std::endl;
}
When I run it, it runs without errors on terminal, but displays no output at all.当我运行它时,它在终端上运行没有错误,但根本不显示任何输出。 I'm not quite sure what I'm doing wrong as when I run other code I've written, similar to this, I don't have a problem.
我不太确定我做错了什么,因为当我运行我编写的其他代码时,与此类似,我没有问题。
What you should have done is create an expx() function and output the result of that.您应该做的是创建一个 expx() 函数并输出其结果。
#include <iostream>
double expx()
{
double x = 1.5;
double expx = 1.0;
double summand = 1.0;
for (int n=1; n <100; ++n)
{
summand *= x/n;
expx += summand;
}
return expx;
}
int main()
{
double value = expx();
std::cout << "final expx from n = 1 to 100 is " << value << std::endl;
}
Anything that you write after a return statement inside a function won't execute.您在函数内的 return 语句之后编写的任何内容都不会执行。 You need to switch the last two lines around, ie:
您需要切换最后两行,即:
std::cout << "final expx from n = 1 to 100 is " << expx << std::endl;
return expx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.