海伦公式参考程序:
#include <iostream>
#include <cmath> // 引入cmath库以使用sqrt函数
using namespace std;
double calculateTriangleArea(int a, int b, int c) {
// 使用海伦公式
double s = (a + b + c) / 2.0; // 半周长
return sqrt(s * (s - a) * (s - b) * (s - c));
}
int main() {
int a, b, c;
// 输入三角形的三条边
cout << "请输入三角形的三条边长 (a, b, c): ";
cin >> a >> b >> c;
// 判断三条边是否能构成三角形
if (a + b > c && a + c > b && b + c > a) {
// 计算并输出面积
double area = calculateTriangleArea(a, b, c);
cout << "三角形的面积是: " << area << endl;
} else {
cout << "输入的边长不能构成一个三角形!" << endl;
}
return 0;
}
深搜判断图的连通性:
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class Graph {
public:
int V; // 顶点数
vector<vector<int>> adjList; // 邻接表
Graph(int V) {
this->V = V;
adjList.resize(V);
}
// 添加边
void addEdge(int u, int v) {
adjList[u].push_back(v);
adjList[v].push_back(u); // 无向图
}
// 深度优先搜索
void dfs(int v, vector<bool>& visited) {
stack<int> s;
s.push(v);
visited[v] = true;
while (!s.empty()) {
int node = s.top();
s.pop();
cout << node << " "; // 输出当前访问的节点
// 遍历邻接的节点
for (int neighbor : adjList[node]) {
if (!visited[neighbor]) {
visited[neighbor] = true;
s.push(neighbor);
}
}
}
}
// 判断图的连通性
bool isConnected() {
vector<bool> visited(V, false);
// 从第一个节点开始DFS
dfs(0, visited);
// 如果所有节点都被访问到,说明图是连通的
for (bool v : visited) {
if (!v) return false;
}
return true;
}
};
int main() {
Graph g(5); // 创建一个包含5个节点的图
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 3);
g.addEdge(3, 4);
if (g.isConnected()) {
cout << "图是连通的" << endl;
} else {
cout << "图是非连通的" << endl;
}
return 0;
}
二分求logx近似值:
#include <iostream>
#include <cmath>
using namespace std;
double log2_binary(double x) {
double left = 0.0, right = x;
double mid;
const double eps = 1e-9;
while (right - left > eps) {
mid = (left + right) / 2;
if (pow(2.0, mid) < x)
left = mid;
else
right = mid;
}
return (left + right) / 2;
}
int main() {
double x;
cout << "请输入一个 >=1 的 x: ";
cin >> x;
if (x >= 1) {
double result = log2_binary(x);
cout << "log2(" << x << ") 的近似值为: " << result << endl;
} else {
cout << "x 必须大于等于 1" << endl;
}
return 0;
}