In your text file write a function that reverses an array of ints: void reverse(int* array, int numElements){ // your code here } Example input: int a[6] = {3,6,8,1,3,6} reverse(a, 6); // should result in {6,3,1,8,6,3}
时间: 2023-03-16 19:44:36 浏览: 102
答案:void reverse(int* array, int numElements){
int i, j, temp;
for (i = 0, j = numElements - 1; i < j; i++, j--) {
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
相关问题
Write a function that reverses its string argument.
好的,下面是一个可以将字符串反转的函数的 Python 代码:
```
def reverse_string(s):
return s[::-1]
```
该函数将字符串作为参数传入,并通过步长为 -1 的切片操作对字符串进行反转,最后返回反转后的字符串。例如:
```
>>> reverse_string("hello world")
'dlrow olleh'
```
Write a Program that reverses the words in a sentence. Enter a sentence: you can cage a swallow can’t you? Reversal of sentence: you can’t swallow a cage can you?
以下是一个使用C++编写的程序,可以将输入的句子中的单词顺序翻转:
```cpp
#include <iostream>
#include <string>
#include <sstream>
#include <algorithm>
using namespace std;
int main() {
string sentence;
cout << "Enter a sentence: ";
getline(cin, sentence);
stringstream ss(sentence);
string word;
string reversed_sentence;
while (ss >> word) {
// 将每个单词插入到结果字符串的开头
reversed_sentence.insert(0, word + " ");
}
// 去掉最后一个空格
reversed_sentence.pop_back();
cout << "Reversal of sentence: " << reversed_sentence << endl;
return 0;
}
```
该程序首先从标准输入中读取一个句子,然后使用stringstream将句子按照空格分割成单词。之后,程序将每个单词插入到结果字符串的开头,最终得到一个单词顺序翻转后的句子。注意,最后一个单词后面不应该有空格,因此需要使用`pop_back()`函数去掉结果字符串的最后一个字符。
阅读全文