【发布时间】:2022-12-18 19:40:56
【问题描述】:
我正在尝试编写一个脚本,用户将在其中输入半径,然后控制台将显示球体的体积和表面积。如果输入半径为负数,则提示用户输入正数半径,直到满足条件。我设法做到了这一点,但没有验证正半径位。我怎样才能做到这一点?
我的代码:
/*
* Calculate the volume and surface area of a sphere.
*
*/
#include <iostream>
#include <string>
#include <sstream>
#include <cmath> // Include cmath for M_PI constant
using namespace std;
int main()
{
const double pi = M_PI; /// Value of PI defined by C++
string input = ""; /// Temporary input buffer
double r = 0.0; /// Sphere radius
double A = 0.0; /// Sphere area
double V = 0.0; /// Sphere volume
// Request radius
cout << "Please enter radius of sphere (positive only): ";
// Get string input from user (up to next press of <enter> key)
getline(cin, input);
// Try to convert input to a double
r = stod(input);
// making sure r is positive
if (r > 0)
{
// Calculate area and volume
// Ensure floating-point division instead of integer division by
// explicitly writing 4.0/3.0
A = 4.0 * pi * r * r;
V = (4.0 / 3.0) * pi * r * r * r;
// Write out result
cout << "Sphere radius: " << r << endl;
cout << "Sphere area: " << A << endl;
cout << "Sphere volume: " << V << endl;
}
else
{
while (r < 0)
{
cout << "Please enter radius of sphere (positive only): " << endl;
}
}
// Return success
return 0;
}
【问题讨论】:
-
如果输入非双精度值,
stod()将使您的程序崩溃。例如“富”。你的评论告诉你你需要做什么。stod()需要在try块内。 -
您需要在 while 循环内调用
getline(cin, input);和r = stod(input);,但是如果您得到一个正数,则需要跳回 ok 部分。制作一个 inout 函数并在其中执行while? -
此外,从 C++20 开始,
<numbers>定义了std::numbers::pi。 -
最后,我的建议是注意获取数据并确保其正确无误,前做任何计算。您部分验证您的输入,进行计算,然后再次检查您的输入。在编写代码之前讨论这些事情。
标签: c++ loops if-statement while-loop conditional-statements