[英]Accessing the integers of an array in C language
如果这是一个基本问题,我很抱歉,但是当我尝试对 [1,2,3,4,5] 之类的数组进行一些操作时,我得到了完全不同的整数,例如 ---> [268501009, 0, 1378144, 0, 0]
我不知道如何解决这个问题。 void function 有什么问题吗?
#include <stdio.h>
#define maxN 30
void rotate(int v[maxN], int n, int p, int dir);
int main() {
int n, v[maxN], tmp;
while (1){
printf("(Number integers in the array) n = "); scanf("%d", &n);
//condition of n
if ((n<=0) || (n > maxN)){
printf("\n*Error! : n should be in the range (0,30]\nPlease try again:\n");
} else{
//enter the elements of the array
printf("\nPlease enter %d integers:\n", n);
for (int i=0; i < n; i++){
scanf("%d", &tmp);
v[i] = tmp;
}
//print the original array
printf("\nThe array is the following:\n");
for(int j=0; j<n; j++){
if (j == 0){
printf("[%d, ", v[j]);
} else if (j == (n-1)){
printf("%d]", v[j]);
} else{
printf("%d, ", v[j]);
}
}
break;
}
}
// print the rotated array
printf("\n\n");
int flag=1;
int dir, p;
while (flag){
printf("\nPlease enter the direction (dir)\n( -1' for Right / '1' for Left) : ");
scanf("%d", &dir);
printf("\nPlease enter the number of iterations 'p' (if [p <= 0] the program will be terminated) : ");
scanf("%d", &p);
if (((dir == -1) || (dir == 1)) && (p > 0)){
rotate(&v[n], n, p, dir);
}else if((dir != -1) && (dir != 1)){
printf("\n*Error!* : dir must be -1 or 1 \nPlease try again:\n");
}
else if(p <= 0){
flag = 0;
}
}
return 0;
}
void rotate(int v[maxN], int n, int p, int dir){
if (dir == -1){ //to the right
int tmp, repeat=0;
while (repeat < p){ //iterate p times
tmp = (int)v[n-1];
for (int i=n-1; 0 <= i < n; i--){ //move to the right one time
if ((i-1) < 0){
v[0] = tmp;
}else{
v[i] = v[i-1];
}
}
repeat++;
}
}
else if (dir == 1){ //to the left
int tmp, repeat=0;
while (repeat < p){ //iterate p times
tmp = (int)v[0];
for (int i=0; i < n; i++){ //move to the right one time
if ((i+1) == n){
v[n-1] = tmp;
}else{
v[i] = v[i+1];
}
}
repeat++;
}
}
//print the rotated array
printf("\nThe array is the following:\n");
for(int j=0; j<n; j++){
if (j == 0){
printf("[%d, ", v[j]);
} else if (j == (n-1)){
printf("%d]", v[j]);
} else{
printf("%d, ", v[j]);
}
}
printf("\n");
}
我在这里看到你的问题,
rotate(&v[n], n, p, dir);
也许您对如何通过 function 发送数组感到困惑。 如果你有一个像这样的数组int v[n]
并且你想通过 function 发送它,你必须这样输入
rotate(v, n, p, dir);
然后在 function
void rotate(int v[maxN], int n, int p, int dir){
这是我在您的 function 中看到的唯一错误,除非您再次获得意外值...阅读有关 arrays 和功能的更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.