用C++编写一个程序,实现从给定的12个饭菜名中随机选择1个
时间: 2024-03-23 12:37:26 浏览: 17
好的,以下是一个简单的 C++ 程序,可以实现从给定的12个饭菜名中随机选择1个:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
// 定义一个字符串数组,存储12个饭菜名
string dishes[12] = {"宫保鸡丁", "鱼香肉丝", "回锅肉", "麻婆豆腐", "红烧肉", "水煮鱼", "糖醋排骨", "酸菜鱼", "辣子鸡", "番茄炒蛋", "蒜泥白肉", "清蒸鲈鱼"};
// 随机种子
srand(time(NULL));
// 随机选择一个饭菜名
int index = rand() % 12;
string chosenDish = dishes[index];
// 输出结果
cout << "今天的晚餐是:" << chosenDish << endl;
return 0;
}
```
该程序首先定义了一个字符串数组 `dishes`,其中存储了12个饭菜名。然后使用 `srand()` 函数和 `time(NULL)` 作为参数,来初始化随机数生成器的种子。接着使用 `rand()` 函数和取模运算符 `%`,在0~11之间随机选择一个下标,从而得到一个随机选择的饭菜名。最后输出结果,提示今天的晚餐是哪个饭菜。
相关问题
用c++编写一个程序,实现对有序数组的折半查找算法。
好的,以下是用C++编写的实现有序数组折半查找算法的程序:
```c++
#include <iostream>
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;
if (arr[mid] < target)
left = mid + 1;
else
right = mid - 1;
}
return -1; // 返回-1表示查找失败
}
int main()
{
int arr[] = { 2, 3, 4, 5, 6, 7, 8, 9 };
int n = sizeof(arr) / sizeof(arr[0]);
int target = 5;
int result = BinarySearch(arr, 0, n - 1, target);
if (result == -1)
cout << "目标元素未找到" << endl;
else
cout << "目标元素在索引 " << result << " 处" << endl;
return 0;
}
```
这个程序中,我们首先定义了一个`BinarySearch()`函数,它接受一个有序数组、数组左右边界以及要查找的目标元素。在函数中,我们使用了一个`while`循环来不断缩小我们要查找的范围,直到找到目标元素或查找失败。
我们在主函数中定义了一个有序数组、数组长度和要查找的目标元素,并且调用了`BinarySearch()`函数来进行查找。如果查找成功,我们输出目标元素的索引;否则输出“目标元素未找到”。
希望这个程序能够帮助你理解折半查找算法。
用c++编写一个程序,实现对数组的顺序查找算法。
好的,下面是一个简单的 C++ 实现,对给定的数组进行线性搜索,返回要查找的元素的下标,如果不存在则返回 -1。
```cpp
#include <iostream>
using namespace std;
int linear_search(int arr[], int n, int x) {
/**
* 在数组 arr 中查找元素 x 的下标
* 如果找到了,返回下标
* 如果没有找到,返回 -1
*/
for (int i = 0; i < n; i++) {
if (arr[i] == x) {
return i;
}
}
return -1;
}
int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = sizeof(arr) / sizeof(arr[0]);
int x = 3;
int result = linear_search(arr, n, x);
if (result == -1) {
cout << "Element not found" << endl;
} else {
cout << "Element found at index " << result << endl;
}
return 0;
}
```
其中,arr 是要查找的数组,n 是数组的长度,x 是要查找的元素。