编写一个读取5个整数元素的程序,存储它们,将它们全部反转并存储在一个单独的数组中。最后打印两个数组。 [英] Write a program which reads 5 integer elements, stores them, reverse them all and store in a separate array. Print both arrays at the end.

查看:47
本文介绍了编写一个读取5个整数元素的程序,存储它们,将它们全部反转并存储在一个单独的数组中。最后打印两个数组。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>
using namespace std;
main(){
	int i,j;
	int arr[i];
	int new_arr[i];
	int number,store=0;
	for(i=0;i<5;i++){
		cout<<"enter the 5-digit element of array : ";
		cin>>number;
		arr[i]=number;
		for(j=0;j<5;j++){
			store=store*10+(number%10);
			number=number/10;
		}
		new_arr[i]=store;
	}
	cout<<"the 5 digit element array is : "<<arr[0]<<" "<<arr[1]<<" "<<arr[2]<<" "<<arr[3]<<" "<<arr[4]<<endl;
	cout<<"the 5 digit element reverse order array is : "<<new_arr[0]<<" "<<new_arr[1]<<" "<<new_arr[2]<<" "<<new_arr[3]<<" "<<new_arr[4]<<endl;
	return 0;
}

推荐答案

您正在将未初始化的变量 i 传递给指定数组大小:

You are passing the uninitialised variable i to specify the array sizes:
int i,j;
int arr[i];
int new_arr[i];



因此,您不知道数组的实际大小。编译器可以用零初始化 i ,这样你的数组就不存在了,你在读取项目时会从堆栈中得到随机值。



为避免此类错误,您应将编译器警告级别设置为最大值并修复代码,直到您没有警告为止。





在你的情况下我会定义一个大小:


As a result, you don't know how large your arrays are actually. The compiler may initialise i with zero so that your arrays did not really exist and you will get random values from the stack when reading items out.

To avoid such mistakes you should set the compiler warning level to maximum and fix your code until you got no warnings.


In your case I would define a size:

const int max_items = 5;
int arr[max_items];
int new_arr[max_items];
// ...
for (i = 0; i < max_items; i++)
// ...







一旦修复了上述内容,你还应该在内部重置 store 之前环。否则,该值将累计在所有五个输入值上:




Once the above has been fixed, you should also reset store before the inner loop. Otherwise the value is cumulated over all five input values:

// Reset store before calculation 
store = 0;
for(j=0;j<5;j++){


这篇关于编写一个读取5个整数元素的程序,存储它们,将它们全部反转并存储在一个单独的数组中。最后打印两个数组。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆