关于数组的问题,跪求大神指点

z8179w 2018-03-11 01:19:24
我是一名C++的初学者,这两天弄一个数组移位的问题,就是将一个数组的内容滚动后移一位,也就是将数组的前一项的内容赋给后一项,数组的最后一项的内容赋给第一项。

编译环境为VS2017,源代码如下, 运行的结果只是将a[9]的值赋给了a[0],其他的项都没有变化。



#include "stdafx.h"
#include <iostream>
using namespace std;



int main()
{
int a[10];
for (int i = 0; i < 10; i++)
{
a[i] = i;
}
cout << endl << "The original array is" << endl;
cout << "a[10] = " << "{ ";
for (int i = 0; i < 10; i++)
{
cout << a[i] << "\t";
}
cout << "}";


int endvalue = a[9];
int i = 9;
while(i <= 1)
{
a[i] = a[i-1];
i--;
}
a[0] = endvalue;

cout << endl << "The new array is" << endl;
cout << "a[10] = " << "{ ";
for (int i = 0; i < 10; i++)
{
cout << a[i] << "\t";
}
cout << "}";

cin.get();
return 0;
}

我反复的看了,没有发现哪里有逻辑错误,请大神指点我的错误之处,谢谢了。
...全文
320 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
自信男孩 2018-03-12
  • 打赏
  • 举报
回复
//#include "stdafx.h"
#include <iostream>

using namespace std;



int main()
{
    int a[10];
    for (int i = 0; i < 10; i++)
        a[i] = i;

    cout << endl << "The original array is" << endl;
    cout << "a[10] = " << "{ ";
    for (int i = 0; i < 10; i++)
    {
        cout << a[i] << "\t";
    }
    cout << "}"<<endl;


    int endvalue = a[9];
    int i = 9;
    while(i >= 1)
    {
        a[i] = a[i-1];
        i--;
    }
    a[0] = endvalue;

    cout << endl << "The new array is" << endl;

    cout << "a[10] = " << "{ ";
    for (int i = 0; i < 10; i++)
        cout << a[i] << "\t";

    cout << "}"<<endl;

    cin.get();
    return 0;
}
参考一下吧
mstlq 2018-03-11
  • 打赏
  • 举报
回复
哈哈,楼主可以结贴咯
z8179w 2018-03-11
  • 打赏
  • 举报
回复
多谢,我也是笨的不行,早知道在循环里插上变量看一看好了。
zhangyiant 2018-03-11
  • 打赏
  • 举报
回复
如果在循环里面打上断点,或者加些debug输出,就很容易发现问题。这种符号写反确实自己不容易看出来。
mstlq 2018-03-11
  • 打赏
  • 举报
回复
#include <iostream>
using namespace std;



int main()
{
    int a[10];
    for (int i = 0; i < 10; i++)
    {
        a[i] = i;
    }
    cout << endl << "The original array is" << endl;
    cout << "a[10] = " << "{ ";
    for (int i = 0; i < 10; i++)
    {
        cout << a[i] << "\t";
    }
    cout << "}";


    int endvalue = a[9];
    int i = 9;
    while (i >= 1)//原来这里符号写反了
    {
        a[i] = a[i - 1];
        i--;
    }
    a[0] = endvalue;

    cout << endl << "The new array is" << endl;
    cout << "a[10] = " << "{ ";
    for (int i = 0; i < 10; i++)
    {
        cout << a[i] << "\t";
    }
    cout << "}";

    cin.get();
    return 0;
}

33,311

社区成员

发帖
与我相关
我的任务
社区描述
C/C++ 新手乐园
社区管理员
  • 新手乐园社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧