【发布时间】:2021-07-20 16:02:47
【问题描述】:
如果这是一个基本问题,我很抱歉,但是当我尝试对 [1,2,3,4,5] 等数组进行一些操作时,我得到的整数完全不同 ---> [268501009 , 0, 1378144, 0, 0]
我不知道如何解决这个问题。 void函数有问题吗?
#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");
}
【问题讨论】:
-
在旋转前的第一部分,数组完美保存。你是说你在旋转之后得到那些随机值吗?
-
代码太多,没有人愿意通读所有这些来找出可能出错的地方。尝试发布Minimal Reproducible Example
-
没错!应用“旋转”功能后,我得到了这些值
-
你为什么将
&v[n]传递给rotate?不应该给rotate数组的起始地址吗? -
我得到了他的错误,所以我添加了 & 符号:“不兼容的整数到指针转换将 'int' 传递给 'int *' 类型的参数;使用 & 获取地址”