0

我的教授希望我将 calculateArea 中的“区域”作为字符/字符串输出。我不确定他到底是什么意思,但也许你们中的一些人可能明白。

#include <iostream>
#include "math.h"
#include <cmath>
#include <sstream>
#include <string>

using namespace std;

const char& calculateArea(double diameter, double chord)
{   
    double length_1, length_2, angle; //This creates variables used by the formula.
    angle = acos( (0.5 * chord) / (0.5 * diameter) ); //This calculates the angle, theta, in radians.
    
    cout << "Angle: " << (angle * 180) / 3.14159 << "\n"; //This code displays the angle, currently in radians, in degrees.
    
    length_1 = (sin(angle)) * 6; //This finds the side of the triangle, x.
    
    cout << "X: " << length_1 << " inches "<< "\n"; //This code displays the length of 'x'.
    
    length_2 = (0.5 * diameter) - length_1; /*This code finds the length of 'h', by subtracting 'x' from the radius (which is half                                              the diameter).*/
    
    cout << "h: " << length_2 << " inches" << "\n"; //This code displays the length of 'h'.
    
    double area = ((2.0/3.0) * (chord * length_2)) + ( (pow(length_2, 3) / (2 * chord) ) ); /*This code calculates the area of the                                                                                                            slice.*/
    ostringstream oss;
    
    oss << "The area is: "<< area << " inches";
    
    string aStr = oss.str();
    
    cout << "Debug: "<< aStr.c_str() << "\n";
    
    const char *tStr = aStr.c_str();
    
    cout << "Debug: " << tStr << "\n";
    
    return *tStr;
    
    //This returns the area as a double.

}

int main(int argc, char *argv[]) {
    
    double dia, cho; //Variables to store the user's input.
    
    cout << "What is your diameter? ";  //
    cin >> dia;                          // This code asks the user to input the diameter & chord. The function will calculate
    cout << "What is your chord? ";      // the area of the slice.
    cin >> cho;                          //
    
    const char AreaPrint = calculateArea(dia, cho); //Sends the input to the function.
    
    cout << AreaPrint; //Prints out the area.
            
    return 0;
}

我得到这样的输出:

你的直径是多少?12

你的和弦是什么?10

角度:33.5573

X:3.31662 英寸

高:2.68338 英寸

调试:面积为:18.8553英寸

调试:面积为:18.8553英寸

我需要弄清楚如何返回 tStr 指向的字符串。如果你不明白我在说什么,对不起,我不确定教授的要求。

4

1 回答 1

1

You are returing a char reference not a string. (the *tStr says 'give me the contents of the pointer')

A more correct version of what you are trying is:

const char* calculateArea(double diameter, double chord)

and

return tStr; // no 'content of'

But this is still bad: the string returned is "out of scope" when aStr goes out of scope, so you really need to return a copy of the characters or just return the string itself (and let the std lib worry about the copy for you)

const string calculateArea(double diameter, double chord)

...

return aStr;
于 2012-02-07T00:49:00.093 回答