0

宿題はほとんど終わりましたが、最後に、"quad.txt" というテキスト ファイルからいくつかの値を読み取り、2 次式で根を計算して値を出力するプログラムを作成する必要があります。 . ラボの最初の部分は、これらすべてを 1 つの関数 main で行うことでした。それはうまくいきます。しかし、今度は 3 つの別個の関数を作成するよう求められます。1 つは判別式 (b^2 -(4*a*c)) を計算し、判別式の値に基づいて文字列値 (正、ゼロ、または負) を返す関数です。 、上記の返された文字列値に基づいて実際のルートと出力を計算する別の関数、そして最後にファイルを開いて他の 2 つの関数を実行する main 関数です。以下の私のコードを参照してください。次に、関数 display() を取得して、返された文字列値を呼び出し、正しいデータを出力します。これまでの私のコードは次のとおりです。

ここに私の quad.txt ファイルquad.txtへのリンクがあります

//Brian Tucker
//5.23.2012
//Lab 6 Part1
//Quadratic Formula from text file

#include <iostream>
#include <fstream>
#include <cmath>
#include <iomanip>
#include <cstdlib>
#include <conio.h>
#include <string>

using namespace std;

int a, b, c; //sets up vars
double r1, r2;

string disc(){
    if((pow(b,2) - (4*a*c) > 0)){ //determines if there are two roots and outputs
    return positive;
    }
    else if((pow(b,2) - (4*a*c) == 0)){ //determines if there is a double root
    return zero;
    }
    else if((pow(b,2) - (4*a*c) < 0)){ //determines if there are no roots
    return negative;
    }
}

void display(string data){
    r1=((-b)+sqrt(pow(b, 2)-(4*a*c)))/(2*a); //quadratic formula
    r2=((-b)-sqrt(pow(b, 2)-(4*a*c)))/(2*a);

    if(positive){
    cout<<setw(3)<<"a="<<a; //outputting a, b, c
    cout<<setw(3)<<"b="<<b;
    cout<<setw(3)<<"c="<<c;
    cout<<setw(7)<<"2 rts";
    cout<<setw(5)<<"r1="<<r1;
    cout<<setw(5)<<"r2="<<r2;
    }
    else if(zero){
    cout<<setw(3)<<"a="<<a; //outputting a, b, c
    cout<<setw(3)<<"b="<<b;
    cout<<setw(3)<<"c="<<c;
    cout<<setw(7)<<"Dbl rt";
    cout<<setw(5)<<"r1="<<r1;
    }
    else if(negative){
    cout<<setw(3)<<"a="<<a; //outputting a, b, c
    cout<<setw(3)<<"b="<<b;
    cout<<setw(3)<<"c="<<c;
    cout<<setw(7)<<"No rts";
    }
    cout<<endl;
}

int main(){
    ifstream numFile; //sets up the file
    numFile.open("quad.txt"); //opens the file

    while(numFile.good()){ //while there are still values in the file, perform the function

    numFile>>a>>b>>c;

    string result = disc();
    display(result);
    }

    numFile.close();

    getch();

    return 0;
}
4

1 に答える 1

0

これを行う方法は、ディスクから std::string を返し、それを引数としてディスプレイに渡し、== を使用して設定値と比較することです。

例えば:

#include <string>
#include <iostream>

std::string valueFunction( int i)
{ 
  if ( i >0 )
   return "positive";
  else
   return "not positive";
}

void resultFunction( std::string data)
{
   if (data == "positive")
      std::cout<<"It was a positive number"<<std::endl;
   else if (data == "not positive")
      std::cout<<"it was not a positive number"<< std::endl;
}

int main()
{  
   int i = 453;
   std::string result = valueFunction(i);
   resultFunction(result);
}
于 2012-05-25T03:34:48.027 に答える