为什么我的函数不接受任何输入并输出任何东西?我希望能够接收用户输入,将其存储在我的数组中,然后打印出存储的值。
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;
}