c++一维数组趣味题目
时间: 2025-02-13 22:10:41 浏览: 27
### 关于C++一维数组的有趣练习题和示例
#### 练习题目:查找最大值及其索引位置
此程序接收一系列整数输入并找出其中的最大值以及该最大值的位置。
```cpp
#include <iostream>
using namespace std;
int main() {
const int SIZE = 10;
int numbers[SIZE];
cout << "Enter " << SIZE << " integers:" << endl;
for (int i = 0; i < SIZE; ++i) {
cin >> numbers[i];
}
int maxIndex = 0;
for (int j = 1; j < SIZE; ++j){
if(numbers[j] > numbers[maxIndex]){
maxIndex = j;
}
}
cout << "The largest number is " << numbers[maxIndex]
<< ", at index " << maxIndex << "." << endl;
}
```
这段代码展示了如何遍历整个数组来找到最大的元素,并记录下它的索引[^1]。
#### 实际应用案例:温度转换工具
创建一个简单的命令行应用程序,它接受摄氏度作为输入并将它们存储在一个数组里;之后可以将这些数值批量转成华氏度输出给用户查看。
```cpp
#include <iostream>
using namespace std;
void convertToFahrenheit(int* celsiusArray, double* fahrenheitArray, int size);
int main(){
const int DAYS_IN_WEEK = 7;
int dailyTemperatures[DAYS_IN_WEEK]; // Store Celsius temperatures here
cout << "Please enter this week's daily high temperature in degrees Celsius."<<endl;
for(int k=0;k<DAYS_IN_WEEK;++k){
cout<<"Day "<<(k+1)<<": ";
cin>>dailyTemperatures[k];
}
double convertedTemps[DAYS_IN_WEEK];
convertToFahrenheit(dailyTemperatures,convertedTemps,DAYS_IN_WEEK);
cout<<"\nHere are those same temperatures expressed as Fahrenheit:"<<endl;
for(int l=0;l<DAYS_IN_WEEK;++l){
cout<<"Day "<<(l+1)<<": "<<convertedTemps[l]<<" F"<<endl;
}
}
// Function definition outside of 'main'
void convertToFahrenheit(int* celsiusArray,double* fahrenheitArray,int length){
for(int m=0;m<length;++m){
*(fahrenheitArray+m)=(*celsiusArray+m)*9.0/5.0+32;
}
}
```
上述例子不仅涉及到了基本的一维数组操作还引入了函数指针的概念用于处理数据变换逻辑.
阅读全文
相关推荐

















