gpt-3.5-turbo-0301· openai
Suzhen/CodeChat
你可以用c++完成“可能的二分法”吗,并运用到函数,封装,文件存储等
- User
你可以用c++完成“可能的二分法”吗,并运用到函数,封装,文件存储等
- Assistant
当然可以。以下是一个C++程序,使用了二分法查找一个有序数组中的元素,并将结果存储在文件中。
#include <iostream> #include <fstream> using namespace std; // 二分法查找有序数组中的元素 int binarySearch(int arr[], int left, int right, int target) { while (left <= right) { int mid = left + (right - left) / 2; if (arr[mid] == target) { return mid; } else if (arr[mid] < target) { left = mid + 1; } else { right = mid - 1; } } return -1; } int main() { int arr[] = {1, 3, 5, 7, 9, 11, 13, 15, 17}; int target = 11; int n = sizeof(arr) / sizeof(arr[0]); // 调用二分法查找目标元素 int result = binarySearch(arr, 0, n - 1, target); // 将结果存储在文件中 ofstream fout("result.txt"); if (fout.is_open()) { if (result == -1) { fout << "Target not found!"; } else { fout << "Target found at index " << result; } fout.close(); } else { cout << "Unable to open file!"; } return 0; }这个程序将数组
{1, 3, 5, 7, 9, 11, 13, 15, 17}中的元素11进行二分法查找,并将结果存储到名为 "result.txt" 的文件中。程序中的binarySearch函数实现了二分法查找,主函数调用该函数并将结果存储在文件中。程序中使用了文件流(ofstream和ifstream)将数据存储到文件中或从文件中读取数据。这是一个基本的示例,实际使用中可能需要更复杂的函数和文件操作。