新手一个简单乘法递归问题求助C++
#include <iostream>#include <cmath>
using namespace std;
void repeat(int, int);
void repeat(int a, int b)
{
int answer;
cin >> answer;
while (answer!=a*b)
{
cout << "Please once again!" << endl;
repeat(a, b);
}
cout << "Yeah!!" << endl;
}
void praise();
void praise()
{
int c = rand() % 4 + 1;
switch (c)
{
case 1:cout << "Very good!\n"; break;
case 2:cout << "Excellent!\n"; break;
case 3:cout << "Nice work!\n"; break;
case 4:cout << "Keep up the good work!\n"; break;
}
}
void criticize();
void criticize()
{
int c = rand() % 4 + 1;
switch (c)
{
case 1:cout << "No no~ again please!\n"; break;
case 2:cout << "Wrong. Try once more\n"; break;
case 3:cout << "Don't give up~\n"; break;
case 4:cout << "No no no.Keep trying!\n"; break;
}
}
int main()
{
cout << "Welcome to 小学生乘法训练~\n";
while (1)
{
int a = rand() % 10, b = rand() % 10;
int answer;
cout <<"\n"<< a << " times " << b << " is ?" << endl;
cin >> answer;
if (answer == a * b)
{
praise();
}
else
{
criticize();
repeat(a, b);
}
}
return 0;
}
是一个循环出简单乘法的例子,
我的思路是如果输入错误执行repeat函数,然后直到对了为止。
可如果一道题出错两次递归就结束不了了?
我哪些写错了呀~
{:10_266:} 本帖最后由 major_lyu 于 2020-3-9 18:46 编辑
把repeat()函数中的while改成if试试。
递归本身就是循环,自己体会一哈。
而且没有必要用递归啊。
void repeat(int a, int b)
{
int answer;
cin >> answer;
while (answer != a * b)
{
cout << "Please once again!" << endl;
cin >> answer;
}
cout << "Yeah!!" << endl;
} 本帖最后由 liuzhengyuan 于 2020-3-9 19:23 编辑
为了方便我把随机数和众多批判表扬话语去掉了。
吧repeat 的 void 改为 int.
加上 return repeat(a, b);
#include<iostream>
#include<cmath>
using namespace std;
int repeat(int a, int b)
{
int answer;
cin >> answer;
while (answer!=a*b)
{
cout << "Please once again!\n" << endl;
return repeat(a, b);
}
cout << "Yeah!!\n" << endl;
return 0;
}
int main()
{
cout << "Welcome to 小学生乘法训练~\n";
while (1)
{
int a = 5, b = 5;
int answer;
cout <<"\n"<< a << " times " << b << " is ?" << endl;
cin >> answer;
if (answer == a * b)
{
cout<<"correct\n";
break;
}
else
{
cout<<"wrong\n";
repeat(a, b);
break;
}
}
} 本帖最后由 major_lyu 于 2020-3-9 19:04 编辑
liuzhengyuan 发表于 2020-3-9 18:49
为了方便我把随机数和众多批判表扬话语去掉了。
吧repeat 的 void 改为 int.
这样就可以加上 return0
呵呵,对不对自己复制代码跑一遍。你写的代码自己跑的试了没。连续输错两次就进入死循环,即使输对了也会一直要求输入。你自己测试一下。 major_lyu 发表于 2020-3-9 18:59
呵呵,对不对自己复制代码跑一遍。
不好意思,刚刚看错了 本帖最后由 liuzhengyuan 于 2020-3-9 19:19 编辑
major_lyu 发表于 2020-3-9 18:59
呵呵,对不对自己复制代码跑一遍。你写的代码自己跑的试了没。连续输错两次就进入死循环,即使输对了也 ...
刚刚弄错了,这应该没问题
#include<iostream>
#include<cmath>
using namespace std;
int repeat(int a, int b)
{
int answer;
cin >> answer;
while (answer!=a*b)
{
cout << "Please once again!\n" << endl;
return repeat(a, b);
}
cout << "Yeah!!\n" << endl;
}
int main()
{
cout << "Welcome to 小学生乘法训练~\n";
while (1)
{
int a = 5, b = 5;
int answer;
cout <<"\n"<< a << " times " << b << " is ?" << endl;
cin >> answer;
if (answer == a * b)
{
cout<<"correct\n";
break;
}
else
{
cout<<"wrong\n";
repeat(a, b);
break;
}
}
}
return repeat(a, b); 谢谢,也谢谢2L老哥
页:
[1]