所以我的函数以降序积分多项式。
例如,3X^3-2x+1 = [3 0 2 1]
当然有限制,但这只是为了练习。
除非我输入一个 0 数组,否则我的积分会一直以 -1 或不正确的形式返回。
这给我带来了另一个问题,当输入前几个数字时,如果我输入一个非数字,它就会卡在我的 goto 循环中。我知道我不应该使用这些,请告诉我如何不使用它。
这是我的代码:
#include <iostream>
#include "eval.h"
int main ()
{
using namespace std; // yes i know using std:: is better... but I got lazy
cout<<"This program takes the coefficients of a polinomial in decreasing \n "
"degree. For example, x^2-1 = [1 0 -1] \n";
// explains to the user what the function does, and how to use it
int columns;
cout<<"Enter The highest degree plus one \n "; // in other words, how many elements the array will have
cin>> columns;
cout<<"Enter Your Coefficients\n ";
float myMatrix[columns]; //This was a code for practice, so I decided to use for loops to get user input
for (int i = 1; i<columns+1; ++i)
{
cin>>myMatrix[i];
}
//Im well aware i could have used other things
float skeletonMatrix[columns+1];
for (int ii = 1; ii< columns+8;++ii) //for loop that injects user array into a skeleton matrix which is one element bigger beacuse of +C
{
skeletonMatrix[ii] = (myMatrix[ii]/(columns+1-ii));
}
cout<<"The Integral is"<<endl;
for (int iii = 1; iii<columns+1; ++iii)
{
if (skeletonMatrix[iii] == 0 )
{
continue;
}
cout<<skeletonMatrix[iii]<<"x^"<<columns+1-iii<<" + ";
}
cout<<"C"<<endl; // Obviously I have not added the +C element because I will do that at another point, for a different purpose
cout<<"Do you wish to Evaluate the Integral??? \n ";
cout<<"Y of yes, N for no";
char chYorN;
tryagain:
cin>>chYorN;
double dScalara;
double dScalarb;
double integral;
switch(chYorN)
{
case 'y':
{
cout<<"Enter where you want the integral \n to be evaluated"<<endl;
cout<<"e.g. from a to b would be a, then b"<<endl;
cin>>dScalara;
cin>>dScalarb;
integral = (eval(columns , dScalarb , myMatrix) - eval(columns , dScalara , myMatrix));
cout<<"The integral is"<< integral <<endl;
break;
}
case 'n':
{
cout<<"Thank you for using my program"<<endl;
break;
}
default: // At the matrix input, input a non number, and the program will go to this for some reason
{
cout<<"Try again Brah";
goto tryagain; // <-----im afraid it has to do with this, please show me how to replace this
}
}
return 0;
}
我的 Eval.h 如下:
#ifndef EVAL_H
#define EVAL_H
#include <math.h>
double eval(int columns, double dScalar, float myMatrix[])
{
double dSum;
for (int i=0; i<columns ; ++i)
{
myMatrix[columns-i]= myMatrix[columns-i]*(pow(dScalar,(double)i)); //evaluates a function at dScalar
}
for (int ii=1; ii<columns+1;++ii) // sums up the different parts
{
dSum+=myMatrix[ii];
}
return dSum;
}
#endif
如果有另一种显示我的数组的方式,请告诉我。我希望我可以连续显示它,而不是一列。
也是一个二维数组。我希望它显示如下:
1 0 2 2 0
0 1 2 3 0
0 0 0 0 1