我对 new , delete 和指针的概念相当陌生,所以对于阅读此内容的人来说,解决方案也许是显而易见的,但老实说我很困惑。
我应该有一个初始化为2个元素的数组,但是当用户输入更多数字时,它将使用 new 运算符不断扩展2个元素,直到用户输入&#34 -1"
虽然我有编码允许数组增长,但是results are disappointing当程序处理数组时返回数组中最小数字与每个其他数字之间的差异。我给出的唯一提示是:&#34;当您更改容量时,您不会从原始数组复制到新数组。&#34;但是,我不知道该怎么做。< / p>
非常感谢正确方向的推动。
#include <iostream>
using namespace std;
int main(){
int *ptr; //pointer to array
int capacity = 2; //capactity of array
int size = 0; //how many ints recorded in array
ptr = new int[capacity];
int tmp = 0;
int *numArray = new int[capacity];
while (true){
cout << "Enter a number: ";
int num;
cin >> num;
if (num == -1) break;
if (size == capacity){
int *temp = new int[capacity + 2];
capacity += 2;
delete[]ptr;
ptr = temp;
}
ptr[size++] = num;
}
int smallest = numArray[0];
// Code to process array and look for smallest number
for (int i = 0; i < capacity; i++){
if (numArray[i] < smallest){
smallest = numArray[i];
}
}
cout << endl << "The smallest number in the array is: " << smallest << endl << endl;
for (int i = 0; i < capacity; i++){
int difference = numArray[i] - smallest;
cout << "The difference between " << numArray[i] << " and the smallest number in the array is : " << difference << endl;
}
system("pause");
}
答案 0 :(得分:3)
在这段代码中
<?php
$execJs = "false";
session_start();
if (isset($_SESSION['variable']) && $_SESSION['variable'] === 0) {
$execJs = "true";
}
?>
<script>
var id = 'whatever';
var execJs = "<?php echo $execJs ?>";
if (execJs === 'true') {
toggle_visibility(id);
}
function toggle_visibility(id) {
var e = document.getElementById(id);
if(e.style.display == 'block')
e.style.display = 'none';
else
e.style.display = 'block';
}
</script>
您创建了一个新数组,但不将现有数组内容复制到其中。
在创建数组后立即添加以下行
if (size == capacity){
int *temp = new int[capacity + 2];
capacity += 2;
delete[]ptr;
ptr = temp;
}
进行计算时,您将在数组中输入值。
或者查看for (int i = 0; i < capacity ; ++i) temp[i] = ptr[i];