c++用if语句和switch多分支选择结构编写一个程序包含三个条件1.求圆面积2.求四则运算3.判断水仙花数
时间: 2024-11-09 16:28:15 浏览: 12
在C++中,你可以使用if-else语句或switch-case结构来根据不同的条件执行不同的操作。这里是一个简单的示例,它会根据用户输入的选择分别计算圆面积、执行四则运算,或者检查是否是水仙花数:
```cpp
#include <iostream>
using namespace std;
double calculateCircleArea(double radius) {
return M_PI * pow(radius, 2);
}
int performArithmetic(int a, int b, char op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b != 0)
return a / b;
else
throw "Error: Division by zero!";
default:
cout << "Invalid operator" << endl;
return 0;
}
}
bool isPerfectNumber(int num) {
int sum = 0;
for (int i = 1; i * i <= num; i++) {
if (num % i == 0) {
sum += i;
if (i * i != num)
sum += num / i;
}
}
return sum == num && num > 1;
}
int main() {
int choice;
cout << "Choose an operation:\n"
<< "1. Calculate circle area\n"
<< "2. Perform arithmetic (+,-,*,/)\n"
<< "3. Check for perfect number\n"
<< "Enter your choice: ";
cin >> choice;
double radius;
int a, b;
char op;
switch (choice) {
case 1:
cout << "Enter the radius: ";
cin >> radius;
cout << "The area of the circle is: " << calculateCircleArea(radius) << endl;
break;
case 2:
cout << "Enter two numbers and an operator (+,-,*,/): ";
cin >> a >> b >> op;
cout << "Result: " << performArithmetic(a, b, op) << endl;
break;
case 3:
cout << "Enter a number to check for being a perfect number: ";
cin >> num;
if (isPerfectNumber(num))
cout << num << " is a perfect number." << endl;
else
cout << num << " is not a perfect number." << endl;
break;
default:
cout << "Invalid choice!" << endl;
}
return 0;
}
```
阅读全文