如何实现C++球体半径输入的正数合法性校验
C++实现球体半径的正数输入校验
你的代码里的负数校验逻辑存在两个问题:一是else块里的while循环是死循环——只重复打印提示,却没有重新读取用户输入更新r的值;二是没处理用户输入非数字的情况(比如字母、符号),这会导致stod抛出异常直接终止程序。
修改思路
- 把输入、转换、校验逻辑整合到一个循环中,只要输入不符合要求(负数或非数字),就持续提示用户重新输入
- 使用
stringstream进行输入转换,方便判断转换是否成功,避免异常 - 循环条件设置为“输入无效”,直到获取到有效的正数半径
修改后的完整代码
/* * 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 bool validInput = false; // 标记输入是否有效 // 循环直到获取有效的正数半径 while (!validInput) { cout << "Please enter radius of sphere (positive only): "; getline(cin, input); stringstream ss(input); // 校验:转换成功 + 输入全为数字 + 半径为正数 if (ss >> r && ss.eof() && r > 0) { validInput = true; } else { cout << "Invalid input! Please enter a positive number." << endl; } } // 计算球体表面积和体积 A = 4.0 * pi * r * r; V = (4.0 / 3.0) * pi * pow(r, 3); // 用pow简化三次方计算,也可保留r*r*r // 输出结果 cout << "Sphere radius: " << r << endl; cout << "Sphere area: " << A << endl; cout << "Sphere volume: " << V << endl; return 0; }
关键修改说明
- 用
validInput布尔变量控制循环,确保只有输入有效时才退出循环 stringstream的ss >> r判断转换是否成功,ss.eof()确保输入的整个字符串都是有效数字(避免类似"123abc"这种部分有效输入),同时检查r > 0保证半径为正- 计算和输出逻辑移到循环外,避免重复代码,结构更清晰
- 可选改用
do-while循环,逻辑上更直观(至少执行一次输入操作):
do { cout << "Please enter radius of sphere (positive only): "; getline(cin, input); stringstream ss(input); if (ss >> r && ss.eof() && r > 0) { validInput = true; } else { cout << "Invalid input! Please enter a positive number." << endl; } } while (!validInput);
内容的提问来源于stack exchange,提问作者SpeedBird
相关产品推荐
相关产品推荐

