c++给定任意四个数,显示他们中最大的那个
时间: 2024-02-21 14:57:44 浏览: 28
好的,您可以使用以下代码来实现:
```c++
#include <iostream>
using namespace std;
int main() {
int a, b, c, d;
cout << "请输入四个数:";
cin >> a >> b >> c >> d;
int max_num = a;
if (b > max_num) {
max_num = b;
}
if (c > max_num) {
max_num = c;
}
if (d > max_num) {
max_num = d;
}
cout << "最大的数是:" << max_num << endl;
return 0;
}
```
这个程序首先提示用户输入四个数,然后通过比较找到最大的那个数并输出。
相关问题
c++给定任意四个数,判断如果最大的那个是否能够被剩下的数整除
好的,您可以使用以下代码来实现:
```c++
#include <iostream>
using namespace std;
int main() {
int a, b, c, d;
cout << "请输入四个数:";
cin >> a >> b >> c >> d;
int max_num = a;
if (b > max_num) {
max_num = b;
}
if (c > max_num) {
max_num = c;
}
if (d > max_num) {
max_num = d;
}
bool is_divisible = false;
if (max_num % (a + b + c + d - max_num) == 0) {
is_divisible = true;
}
if (is_divisible) {
cout << "最大的数能够被剩下的数整除" << endl;
} else {
cout << "最大的数不能被剩下的数整除" << endl;
}
return 0;
}
```
这个程序首先提示用户输入四个数,然后通过比较找到最大的那个数。接着,通过判断最大的数能否被剩下的三个数之和整除,确定是否满足题目要求,并输出结果。
C++编程:给定10个有序整数,存入数组a中,编写折半查找函数,完成C++编程:给定10个有序整数,存入数组a中,编写折半查找函数,完成查找任意关键字key查找
以下是C++代码实现:
```
#include <iostream>
using namespace std;
int binarySearch(int arr[], int left, int right, int key) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == key) {
return mid;
}
else if (arr[mid] < key) {
left = mid + 1;
}
else {
right = mid - 1;
}
}
return -1;
}
int main() {
int arr[10] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
int key = 7;
int index = binarySearch(arr, 0, 9, key);
if (index != -1) {
cout << "The index of " << key << " is " << index << endl;
}
else {
cout << "Key not found." << endl;
}
return 0;
}
```
首先定义了一个名为binarySearch的函数,它接受四个参数:数组arr,查找区间的左右边界left和right,以及要查找的关键字key。在函数体内,使用while循环进行折半查找,如果找到了关键字key,就返回它的下标;如果没找到,则返回-1。
在主函数中,定义了一个包含10个有序整数的数组arr,以及要查找的关键字key。调用binarySearch函数进行查找,如果查找成功,输出关键字key的下标;否则输出“Key not found.”。