初次面对c++
第一次实验
2-4源码:
#include<iostream>
using namespace std;
int main()
{
int day;
cin>>day;
switch(day)
{
case 1:
cout<<"workday.Let's work hard";
break;
case 2:
cout<<"workday.Let's work hard";
break;
case 3:
cout<<"workday.Let's work hard";
break;
case 4:
cout<<"workday.Let's work hard";
break;
case 5:
cout<<"workday.Let's work hard";
break;
case 6:
cout<<"weekend.Let's have a rest";
break;
case 7:
cout<<"weekend.Let's have a rest";
break;
break;
}
return 0;
}
运行结果
2-6源码
#include<iostream>
using namespace std;
int main()
{
int a,b=0,t;
cin>>a;
do
{
b+=a%10;
b*=10;
a=a/10;
}while(a!=0);
cout<<b/10;
return 0;
}
运行结果
实验总结和体会
*1 实验需要不停的去尝试,例如在2-6中书本的源码,一开始没有理解在do循环中每执行一次就打印一次的想法。想到的是直接打印出来一个数,因此就有了和书上不一样的源码。。
但依然没有作到最佳的算法,因为我最后需要再做一次除法,才能得到我想要的数。
*2 一个程序可以用不同的算法去做,因为一般用循环可以做的事,都可以用递归算法来做,所以尝试着去试了一下递归,但2-6 的递归不知道哪里出错,感觉对递归的理解还是有偏差。
虽然用递归不会方便很多,而且占了更多的存储空间,希望还是能指点一下。
ps错误的递归算法
#include<iostream>
using namespace std;
int fun(int )
{
int n,b=0;
if(n!=0)
{
b+=n%10;
b*=10;
n/10;
fun(n);
}
return b/10;
}
int main()
{
int n;
cin>>n;
cout<<(fun(n));
return 0;
}