【编程日记】2022.4.19 依靠输出调试,考虑特殊情况

解决洛谷P1957口算练习题

代码:

#include <iostream>
#include <string>
#include <istream>
#include <cmath>

using namespace std;

int main()
{
	//cout<<"HHello, world!"<<endl;
	int n,x[55]={0},y[55],ans[55];
	char opr[55];
	string a,type;
	
	scanf("%d",&n);
	
	for(int i=0;i<n;i++)
	{
		cin>>a;
		if(a.compare("a")==0||a.compare("b")==0||a.compare("c")==0)
		{
			type=a;
			cin>>x[i]>>y[i];
			if(type.compare("a")==0)
			{
				ans[i]=x[i]+y[i];
			}
			if(type.compare("b")==0)
			{
				ans[i]=x[i]-y[i];
			}
			if(type.compare("c")==0)
			{
				ans[i]=x[i]*y[i];
			}
		}
		else
		{
			//cout<<"the input string is : "<<a<<". It's length is: "<<a.length()<<"."<<endl;
			int l=a.length(),j=0;
			while(--l>=0)
			{
				x[i]+=(a[l]-'0')*pow(10,j);
				j++;
				//cout<<"the value of a[l] is: "<<a[l]<<". The value of a[l]-'0' is: "<<a[l]-'0'<<". The value of pow(10,l) is: "<<pow(10,l)<<"."<<endl;
				//cout<<"the value of x[i] adds up to: "<<x[i]<<". The value of l drops to: "<<l<<"."<<endl;
			}
			//cout<<"the value got from the input string is :"<<x[i]<<endl;
			//the code above need modification, for it calculates x[i] wrongly.
			cin>>y[i];
			if(type.compare("a")==0)
			{
				ans[i]=x[i]+y[i];
			}
			if(type.compare("b")==0)
			{
				ans[i]=x[i]-y[i];
			}
			if(type.compare("c")==0)
			{
				ans[i]=x[i]*y[i];
			}			
		}
		switch(type[0])
		{
			case 'a':
				opr[i]='+';
				break;
			case 'b':
				opr[i]='-';
				break;
			case 'c':
				opr[i]='*';
				break;
		}
	}
	for(int i=0;i<n;i++)
	{
		int dig=0,dec=1;
		while(x[i]/dec!=0)
		{
			dig++;
			dec*=10;
		}
		dec=1;
		while(y[i]/dec!=0)
		{
			dig++;
			dec*=10;
		}
		dec=1;
		while(ans[i]/dec!=0)
		{
			dig++;
			dec*=10;
		}
		if(ans[i]<0)
		{
			dig++;
		}
		if(x[i]==0)
		{
			dig++;
		}
		if(y[i]==0)
		{
			dig++;
		}
		if(ans[i]==0)
		{
			dig++;
		}
		dig+=2;
		cout<<x[i]<<opr[i]<<y[i]<<"="<<ans[i]<<endl<<dig<<endl;
	}
	
	return 0;
}

上一篇文章中的代码改动了三处:

1)pow(10,l)改成了pow(10,j), 指数递减改成了递增,纯属逻辑错误

2)x[55]忘记初始化了,后面直接进行运算;改动是把它初始化为零。以后要注意数组的初始化问题。

3)在计算算式长度时考虑了数字为零的特殊情况,数字为零时长度另外加一。因此提醒我们,进行程序设计时对于特殊的输入要充分考虑是否需要进行专门处理,这样才能增加程序的健壮性。

发现前面两处错误的方法是通过多次运行程序观察报错规律,发现总是当前面没有字母时第一个输入的数字出错,由此锁定程序应当是在else处出错,然后在这附近输出程序运行过程中各个变量的值,弄清楚究竟是哪一步出错。

因此,调试程序的方法应该是:输出->定位->再输出->再定位,直到发现错误在哪里。

另外,这道题的调试是我第一次用记事本和开发人员命令提示符来调试,这种原始的方法感觉反而很好,视觉效果很清爽,而且developer command promt窗口每次程序运行的结果都会记录下来,不像console控制台窗口每次运行完毕即退出,运行结果也清空,以后可以继续采用notepad+developer command promt进行调试。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值