简体   繁体   English

C ++,代码工作正常,但在提取函数时无法正常工作

[英]C++, code works fine but not when extracting a function

First of all, I am a physics student, not a programmer so please forgive this trivial problem. 首先,我是物理专业的学生,​​而不是程序员,所以请原谅这个琐碎的问题。 I am trying to create a function to find the roots of a cubic equation using the Newton Raphson method. 我正在尝试创建一个函数,以使用牛顿拉夫森方法找到三次方程的根。 I have created code that pretty much works just fine but the point of the exercise is to have this code in 'function' form, ie return type, parameters then code block. 我已经创建了几乎可以正常工作的代码,但是练习的重点是使该代码具有“函数”形式,即返回类型,参数然后是代码块。 When I try to put it into this form my code will compile but when i input into it the results (roots which it returns) are jibberish. 当我尝试将其放入这种形式时,我的代码将被编译,但是当我将其输入时,结果(返回的根)是乱码。 Here is my code. 这是我的代码。

#include<iostream>
#include<cmath>

double roots(double,double,double,double);

int main()
{
    double x3,x2,x,con;
    std::cin>>x3,x2,x,con;

    double result=roots(x3,x2,x,con);
    std::cout<<result<<std::endl;
    system("pause");
}

double roots(double xcubecoeff, double xsquarecoeff, double xcoeff, double constant)
{
    int j=0;
    int k=0;
    int l=0;
    int m=0;
    double seedvalue1=-10;
    double seedvalue2=10;
    double seedvalue3=0.3;
    double seedvalue4=-0.3;
    double xnplus1;
    double xnplus2;
    double xnplus3;

    while(j <= 100)
    {
        //func is just the structure of the cubic equation in terms of the 
        // parameters of the function
        //derfunc is just the structure of the gneral derivitive of a cuic
        // function, again in terms of the parameters
        //seedvalues are just the initial values for x in the general cubic
        // equation. 
        //Seedvalue one goes into the loop to find the negative x root, 
        // seedvalue 2 finds the positive one, seedvalue three attempts to
        // find the one in the middle of those, however if it just finds
        // either of those again then an IF statement and seedvalue 4 are
        //used to find it.

        double func = xcubecoeff * (seedvalue1 * seedvalue1 * seedvalue1) +
                      xsquarecoeff * (seedvalue1 * seedvalue1) + 
                      xcoeff * seedvalue1 + 
                      constant;

        double derfunc = 3 * xcubecoeff * (seedvalue1 * seedvalue1) +
                         2 * xsquarecoeff * seedvalue1 + 
                         xcoeff;


        double xnplus1 = seedvalue1 - (func / derfunc);

        seedvalue1=xnplus1;
        j++;
    }


    while(k <= 100)
    {
        double func = xcubecoeff * (seedvalue2 * seedvalue2 * seedvalue2) + 
                      xsquarecoeff * (seedvalue2 * seedvalue2) + 
                      xcoeff * seedvalue2 +
                      constant;

        double derfunc = 3 * xcubecoeff * (seedvalue2 * seedvalue2) + 
                         2 * xsquarecoeff * seedvalue2 +
                         xcoeff;

        double xnplus2 = seedvalue2 - (func / derfunc);

        seedvalue2 = xnplus2;
        k++;
    }

    while(l<=100)
    {
        double func = xcubecoeff * (seedvalue3 * seedvalue3 * seedvalue3) + 
                      xsquarecoeff * (seedvalue3 * seedvalue3) +
                      xcoeff * seedvalue3 +
                      constant;

        double derfunc = 3 * xcubecoeff * (seedvalue3 * seedvalue3) + 
                         2 * xsquarecoeff * seedvalue3 + 
                         xcoeff;

        double xnplus3 = seedvalue3 - (func / derfunc);

        seedvalue3=xnplus3;
        l++;
    }

    if(seedvalue3 == seedvalue1 || seedvalue3 == seedvalue2)
    {
        while(m<=100)
        {
            double func = xcubecoeff * (seedvalue4 * seedvalue4 * seedvalue4) +
                          xsquarecoeff * (seedvalue4 * seedvalue4) + 
                          xcoeff * seedvalue4 +
                          constant;

            double derfunc = 3 * xcubecoeff * (seedvalue4 * seedvalue4) +
                             2 * xsquarecoeff * seedvalue4 + xcoeff;

            double xnplus4 = seedvalue4 - (func / derfunc);

            seedvalue4=xnplus4;
            m++;
        }

        std::cout<<seedvalue1<<std::endl;
        std::cout<<seedvalue2<<std::endl;
        std::cout<<seedvalue4<<std::endl;
    }
    else
    {

        std::cout<<seedvalue1<<std::endl;
        std::cout<<seedvalue2<<std::endl;
        std::cout<<seedvalue3<<std::endl;
    }
}

This is probably a really clunky and cumbersome code and I'm sure there is a better way to perform the Newton Raphson method. 这可能是一个非常笨拙且繁琐的代码,我敢肯定有一种更好的方法来执行Newton Raphson方法。 So to be clear, I start by including the standard iostream and math. 为了清楚起见,我首先包括标准的iostream和数学。 Then I declare my function, the name followed by the parameter types that can be passed to it. 然后声明我的函数,其名称后面是可以传递给它的参数类型。 Next I begin my code. 接下来,我开始我的代码。 I initialise the variables x3, x2, x and con as doubles and use the import 'cin' to allow users to input values for these, which will be the coefficients of the cubic equation. 我将变量x3,x2,x和con初始化为双精度变量,并使用导入'cin'允许用户输入这些值,这将是三次方程式的系数。 Next I call the function and put the variable names initialised above which I believe then means that the users inputted values will be passed into the function for use within the function. 接下来,我调用该函数,并将变量名放在上面进行初始化,然后我相信这意味着用户输入的值将被传递到该函数中以供在该函数中使用。 Below this I programme it to print the output of the function. 在此之下,我对其进行编程以打印功能的输出。 Under that is the definition of the function which apart from the function name and parameters is how I wrote it in a different cpp which worked just fine, it was only when I wrote this code, trying to put the original code into function form that the problems occurred. 在此之下是函数的定义,除了函数名和参数之外,我是如何在另一个可以正常工作的cpp中编写它的,只是当我编写此代码时,试图将原始代码放入函数形式中,发生问题。

As I say this code is probably very ugly and inefficient but it does work to some extent, I just cant work out why it doesnt work in this form. 正如我说的那样,这段代码可能很丑陋且效率低下,但在一定程度上确实有效,我无法弄清楚为什么它不能以这种形式工作。

I hope you can help, 希望您能提供帮助,

I will try and clarify if you have any further questions. 我将尝试澄清您是否还有其他问题。

您的函数需要返回一个值,最后缺少一个return语句:

return value; // instead of "value", pick the variable you want to return

The following is wrong: 以下是错误的:

double x3,x2,x,con;
std::cin>>x3,x2,x,con;

This invokes the comma operator which doesn't do what you think it does. 这将调用逗号运算符 ,该运算符不会执行您认为的操作。

You should do this: 你应该做这个:

std::cout << "Enter x3: ";
std::cin >> x3;
std::cout << "Enter x2: ";
std::cin >> x2;
std::cout << "Enter x: ";
std::cin >> x;
std::cout << "Enter c: ";
std::cin >> con;

If you want to combine them into a single line: 如果要将它们合并为一行:

std::cin >> x3 >> x2 >> x >> con;

One problem is with this line 一个问题是这条线

std::cin>>x3,x2,x,con;

This isn't doing what you think it is! 这不是您想的那样! The commas here are actually the "comma operator" which evaluates both its operands and takes on the value of the rightmost one. 这里的逗号实际上是“逗号运算符”,它评估两个操作数并采用最右边一个的值。 It has lower precedence than >> so your line means the same as 它的优先级比>>低,因此您的行与

((((std::cin>>x3), x2), x), con);

which reads from cin into x3 and then goes on to evaluate the variables x2 , x and con - this doesn't do anything because evaluating a variable has no side-effects. 它从cin读取到x3 ,然后继续评估变量x2xcon这没有任何作用,因为评估变量没有副作用。 To read into all 4 variables you can use: 要阅读所有4个变量,可以使用:

std::cin >> x3 >> x2 >> x >> con;

It's a good idea to turn on as many compiler warnings as possible because it will often pick up on things like this. 最好打开尽可能多的编译器警告,因为它经常会遇到这种情况。 For example if I compile those lines of your code with gcc -Wall -Wextra it gives these warnings: 例如,如果我使用gcc -Wall -Wextra编译您的代码行,则会给出以下警告:

test.cpp: In function 'int main()':
test.cpp:5:17: warning: right operand of comma operator has no effect [-Wunused-value]
test.cpp:5:19: warning: right operand of comma operator has no effect [-Wunused-value]
test.cpp:5:22: warning: right operand of comma operator has no effect [-Wunused-value]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C++ 代码在台式机上运行良好,但在笔记本电脑上却不行 - C++ code works fine on desktop but not on the laptop 将代码链接到exe时C ++程序崩溃,但是将代码编译到exe时工作正常,为什么呢? - C++ program crashes when code is linked to exe but works fine when code is compiled into exe, how come? C ++代码可以正常工作,但从Java(JNI)调用时不起作用 - C++ code works fine but doesn't work when calling from Java (JNI) C ++-当我使用sprintf()函数时程序崩溃(std :: cout正常工作) - C++ - Program crashes when I use sprintf() function (std::cout works fine) 涉及向量的C ++代码在Visual Studio上运行良好,而在Linux上则无法正常运行 - C++ code involving vector works fine on visual studio and not on linux 在C ++中工作正常,但在C中运行时错误 - Works fine in C++, but runtime error in C 与C ++ Server连接时C#客户端暂停,但与C#Server连接时工作正常 - C# Client halted while connecting with C++ Server, but works fine when connecting with C# Server 使用RegExp的非常简单的C ++代码在Android上崩溃但在OS X上运行良好 - Very simple C++ code with RegExp crashes on Android but works fine on OS X C ++代码在msdev 6.0中工作正常,在Visual Studio 2010中崩溃 - C++ code works fine in msdev 6.0 and crashes in Visual Studio 2010 使用sublime-build时无法运行C ++程序,从终端运行时可以正常工作 - Cannot run C++ program when using sublime-build, works fine when running from terminal
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM