为什么我的函数不接受任何输入和输出任何东西?我希望能够接收用户输入,将其存储在我的数组中,然后打印出存储的值。
using namespace std;
void Memory(){
int temp;
int Mange[3] = {0, 0, 0};
for(int i = 0; i < sizeof(Mange); i++){
cin >> temp;
temp = Mange[i];
cout << Mange[i];
}
}
int main() {
Memory();
return 0;
}
如果您刚刚开始熟悉使用数组,这是一个很好的练习,对您有好处!这就是我实现一个程序的方式,该程序将接受用户输入到数组中,然后打印数组中的每个元素(请务必阅读注释!
#include <iostream>
using namespace std;
const int MAXSIZE = 3;
void Memory(){
//initialize array to MAXSIZE (3).
int Mange[MAXSIZE];
//iterate through array for MAXSIZE amount of times. Each iteration accepts user input.
for(int i = 0; i < MAXSIZE; i++){
std::cin >> Mange[i];
}
//iterate through array for MAXSIZE amount of times. Each iteration prints each element in the array to console.
for(int j = 0; j < MAXSIZE; j++){
std::cout << Mange[j] << std::endl;
}
}
int main() {
Memory();
return 0;
}
我希望这有帮助!了解此程序实际执行操作的一个好方法是将其复制并粘贴到 IDE 中,然后对代码运行调试器并逐行观察发生的情况。
我自己一开始在启动数组时就这样做了,然后掌握了窍门。你做对了一半的程序,这很好,你犯的唯一错误是将输入数据存储在适当的变量中并以错误的格式显示它们 要解决此问题,
#include<iostream>
using namespace std;
const int size=3;
void Memory()
{
// You don't need variable temp here
int Mange[size] = {0, 0, 0};
//It's not necessary to keep it zero but it's a good practice to intialize them when declared
for(int i = 0; i < size; i++)
//You can store maximum value of array in diff variable suppose const then use it in condition
{
cin >> Mange[i];
cout << Mange[i];
//You can print it later with a different loop
}
}
int main() {
Memory();
return 0;
}