C++之我的错误篇(一)
2021/10/14 20:16:27
本文主要是介绍C++之我的错误篇(一),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
问题描述:在打印数组时,前面的数字成功打印,后面的出现错误(打印出地址来)
代码如下:
#include <iostream> #include "malloc.h" #include "stdlib.h" #define OK 1 #define OVERFLOW -1 #define ERROR 0 #define QMAXSIZE 23//定义长度,长度>=输出行数+3 typedef int ElemType; typedef int Status; using namespace std; typedef struct { ElemType *base; //初始化的动态分配存储空间 int f_ront; //头指针,队列不空指向队列头元素 int rear; //尾指针,队列不空指向队列尾元素下一位置 }SqQueue; Status InitQueue(SqQueue &Q) {//构造空队列 Q.base = new ElemType[QMAXSIZE]; if (!Q.base) exit (OVERFLOW); Q.f_ront=Q.rear=0; return OK; } ElemType QueueLength(SqQueue Q) {//获取队列长度 return (Q.rear-Q.f_ront+QMAXSIZE)%QMAXSIZE; } void GetHead(SqQueue Q,ElemType &e) {//返回队头元素 if(Q.f_ront == Q.rear) e=0; else e=Q.base[Q.f_ront]; } Status EnQueue(SqQueue &Q,ElemType e) {//插入元素 if((Q.rear+1)%QMAXSIZE==Q.f_ront) return ERROR; Q.base[Q.rear]=e; Q.rear=(Q.rear+1)%QMAXSIZE; return OK; } Status DeQueue(SqQueue &Q,ElemType &e) {//删除元素 if(Q.f_ront==Q.rear) return ERROR; e=Q.base[Q.f_ront]; Q.f_ront=(Q.f_ront+1)%QMAXSIZE; return OK; } Status QueueEmpty(SqQueue &Q) {//判断队列是否为空 if(Q.f_ront==Q.rear) return OK; else return ERROR; } void PrintQueue(SqQueue Q, ElemType n) {//遍历循环队列,并打印所有元素 cout<<"第"<<n<<"行:"; ElemType x=Q.f_ront%QMAXSIZE; while(x%QMAXSIZE!=Q.rear){ cout<<Q.base[x]<<"\t"; x++; //更正后为x=(x+1)/QMAXSIZE } } void YangHui(int n) {//杨辉三角 SqQueue Q; ElemType j,s,t; printf("第1行:1\n"); InitQueue(Q); EnQueue(Q,0); /*开始*/ EnQueue(Q,1); /*第1行*/ EnQueue(Q,1); for(j=2;j<n;j++) //从第二行开始循环到n-1行 { EnQueue(Q, 0); /*第j行的结束符*/ printf("第%d行:",j); do { DeQueue(Q,s); GetHead(Q,t); if(t) printf("%d\t",t); /*非0输出,否则换行*/ else printf("\n"); EnQueue(Q,s+t); } while(t!=0); /*遇到结束符前循环*/ } DeQueue(Q,s); //输出最后一行 PrintQueue(Q,j); } main() { ElemType n; while(true) { printf("请输入输出的行数(小于等于%d):",QMAXSIZE-3); scanf("%d",&n); if(n<=(QMAXSIZE-3)&&n>1) { YangHui(n); break; } else printf("输入错误,请重新输入\n"); } }
由于是在最后一行输出出现问题,我便开始检查输出最后一行的代码,但是看来看去就没错。最后设置断点调试,发现到后面,Q.base[QMAXSIZE]数组已经越界,QMAXSIZE=23。所以造成Q.base的值输出是一个结果。
将x++改成x=(x+1)/QMAXSIZE后输出正确
新手,欢迎大家指正
这篇关于C++之我的错误篇(一)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-21拼接的xml报文,尖括号都被转移成了< 是什么原因-icode9专业技术文章分享
- 2024-09-21Svg Sprite Icon教程:从入门到实践
- 2024-09-21Svg Sprite Icon实战:从入门到上手
- 2024-09-20构建一个多PDF RAG聊天机器人:使用Langchain和Streamlit及代码
- 2024-09-20whatsapp webhook 回调的签名验证偶尔会失败是什么原因-icode9专业技术文章分享
- 2024-09-19Excel数据导出课程:初学者必备教程
- 2024-09-19Excel数据导入课程:新手入门指南
- 2024-09-19RBAC的权限管理入门教程
- 2024-09-19如何使用Svg Sprite Icon制作图标
- 2024-09-19uniapp 如何实现点赞后全局更新数据-icode9专业技术文章分享