gpt4 book ai didi

c++ - 返回字符串流 (char*)

转载 作者:行者123 更新时间:2023-11-28 08:10:40 28 4
gpt4 key购买 nike

我的教授要我将 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;
}

虽然我得到的输出是这样的:

What is your diameter? 12

What is your chord? 10

Angle: 33.5573

X: 3.31662 inches

h: 2.68338 inches

Debug: The area is: 18.8553 inches

Debug: The area is: 18.8553 inches

T

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

最佳答案

您正在返回一个字符引用而不是一个字符串。(*tStr 说'给我指针的内容')

您正在尝试的更正确的版本是:

const char* calculateArea(double diameter, double chord)

return tStr; // no 'content of'

但这仍然很糟糕:当 aStr 超出范围时,返回的字符串“超出范围”,因此您确实需要返回字符的拷贝或只返回字符串本身(让标准库担心给你的拷贝)

const string calculateArea(double diameter, double chord)

...

return aStr;

关于c++ - 返回字符串流 (char*),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9169543/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com