【发布时间】:2019-03-30 10:41:48
【问题描述】:
一旦满足两个条件,我正试图让我的 for 循环停止运行。 n 柜台没有给我问题。我基本上希望循环在循环开始后一旦totalSum 等于自身(或在自身的一定范围内)就停止运行。 我是编码初学者并且是这个网站的新手,所以我提前道歉。为了代表任何人进行测试,我将完整地包含代码。
我将在此处提供更多信息。我的代码按原样运行,尽管在循环期间,计算的值变得很大,我得到一些东西说nan 或inf。在打印出totalSum 等之后。我看到我得到了重复一次或两次的值(正确的正弦计算),但在那之后,数字不断增加或减少循环。一旦我的循环最终在 100 次后结束,我就会得到上述nan/inf。
long double sine(double x)
{
long double totalSum = 0.0;
for(int n = 0; n < 100; ++n)
{
int plusOrMinusSign = pow(-1, n);
long double num = pow(x,(2 * n + 1));
long double den = factorialtest(2 * n + 1);
totalSum += (plusOrMinusSign * num / den);
cout <<plusOrMinusSign<<" "<< x << "^" <<(2*n+1) <<"/"<< (2 * n + 1)<<"! = " << totalSum <<endl; //testing purposes
}
return totalSum;
}
下面的整个程序
#include <iostream>
#include <cmath> //used for pow indicated in comment with "^"
#include <iomanip>
using namespace std;
long int factorialtest(int x) //calculates factorial
{
long int factorialNum = 1;
for(int count = 1; count <= x; count++)
factorialNum = factorialNum * count;
return factorialNum;
}
long double sine(double x)
{
long double totalSum = 0.0;
for(int n = 0; n < 100; ++n)
{
int plusOrMinusSign = pow(-1, n);
long double num = pow(x,(2 * n + 1));
long double den = factorialtest(2 * n + 1);
totalSum += (plusOrMinusSign * num / den);
cout <<plusOrMinusSign<<" "<< x << "^" <<(2*n+1) <<"/"<< (2 * n + 1)<<"! = " << totalSum <<endl; //testing purposes
}
return totalSum;
}
double cosine(double x) //returns cos of x
{
double totalSum = 0;
for(int n = 0; n < 100; n = n + 2)
{
double num = pow(x,(n)); // ^ used pow here, does the power of x to the n value above
double den = factorialtest(n); //used my own factorial program here, multiplies n by factorial of n
totalSum = totalSum + ( num / den);
}
return totalSum = 0;
}
double tangent(double x) { //returns tangent
return sine(x) / cosine(x);
}
double secant(double x) { //returns secant
return 1 / cosine(x);
}
double cosecant(double x) { //returns cosecant
return 1 / sine(x);
}
double cotangent(double x) { //returns cotangent
return 1 / tangent(x);
}
int main() {
double x;
cout << "Input number to find sine: ";
cin >> x;
cout << "Sine of " << x << " is " << sine(x) << endl;
}
顺便说一句,程序计算弧度。下面使用 1 表示 x 发生的事情的示例。 “正弦(1)”
-1 1^63/63! = 0.841471
1 1^65/65! = 0.841471
-1 1^67/67! = -inf
在某一点之后,它给了我。感谢您的宝贵时间。
【问题讨论】:
-
TL;DR - 你知道你可以有一个布尔表达式作为循环中的条件,如
for (x = 0; x < 100 && y != z; ++x)? -
感谢您的快速回复。是的,我知道我可以有正确或错误的表达,这是我最初尝试做的。这是
for( int n = 0, totalSum = 0; n < 100; ++n; totalSum != totalSum)但我知道 for 是一个预先测试的循环并且不会运行,因为它已经等于它自己。还有就是写错了,那是我的无知。 -
你想用什么作为第二个条件?
-
两者
;之间的一切都是你的表达。像这样写:for( int n = 0, totalSum = 0; n < 100 && totalSum != totalSum; ++n )(编辑:仅供参考:totalSum != totalSum 不会是真的 - 所以修正你的逻辑。但这就是你刚刚要求的,所以我只是在这里跟随你的领导。) -
我想使用
totalSum作为第二个条件,在错误发生之前停止循环。对于之前的回复,我读错了你的问题。所以不,我不明白这将如何工作,但我会通过查找这些操作数的定义来教育我自己。
标签: c++ math trigonometry taylor-series