用c++编写一个程序,求半圆的面积
时间: 2023-04-10 20:01:17 浏览: 127
好的,这个问题我可以回答。以下是求半圆面积的 C 语言程序:
#include <stdio.h>
#define PI 3.1415926535
int main()
{
float r, area;
printf("请输入半径:");
scanf("%f", &r);
area = 0.5 * PI * r * r;
printf("半圆的面积为:%f\n", area);
return 0;
}
希望能帮到你!
相关问题
用C++编写一个程序来计算矩形的面积。
一个简单的 C++ 程序可以使用以下代码来计算矩形的面积:
```
#include <iostream>
using namespace std;
int main() {
double width, height;
cout << "Enter the width of the rectangle: ";
cin >> width;
cout << "Enter the height of the rectangle: ";
cin >> height;
double area = width * height;
cout << "The area of the rectangle is: " << area << endl;
return 0;
}
```
这个程序先从用户处读取矩形的宽和高,然后计算矩形的面积并输出结果。
如果要编写一个面向对象的程序来计算矩形的面积,可以创建一个 Rectangle 类,其中包含成员变量 width 和 height,以及成员函数 getArea(),如下所示:
```
class Rectangle {
private:
double width;
double height;
public:
Rectangle(double w, double h) {
width = w;
height = h;
}
double getArea() {
return width * height;
}
};
```
然后在 main 函数中创建一个 Rectangle 对象,调用它的 getArea() 函数来计算矩形的面积,如下所示:
```
int main() {
double width, height;
cout << "Enter the width of the rectangle: ";
cin >> width;
cout << "Enter the height of the rectangle: ";
cin >> height;
Rectangle rect(width, height);
double area = rect.getArea();
cout << "The area of the rectangle is: " << area << endl;
return 0;
}
```
输出结果与之前的程序相同。
使用c++编写一个时钟程序
下面是一个简单的使用C++编写的时钟程序示例,它会每秒钟更新一次当前时间并输出:
```c++
#include <iostream>
#include <ctime>
#include <chrono>
#include <thread>
using namespace std;
int main() {
while (true) {
auto now = chrono::system_clock::now();
time_t t = chrono::system_clock::to_time_t(now);
cout << "Current time: " << ctime(&t);
this_thread::sleep_for(chrono::seconds(1));
}
return 0;
}
```
程序使用了chrono库来获取当前时间,并使用ctime库将time_t类型转换为可读的时间字符串进行输出。使用this_thread::sleep_for函数来让程序每秒钟更新一次时间。