我正在通过MOOC进行有关c ++的介绍,并陷入有关函数的练习中。该练习是关于一个程序,该程序将数字更改为读取的方式。
例如:
“ 1”的读法类似于“一个”,因此下一个数字应为
读为“ 2”的“ 11”下一个数字是
“ 21”->“一二一一”
“ 1211”->“一个1和一个1以及两个2”
“ 111221”->“三二二一一一”
“ 312211” .....等
用户应提供起始编号和执行此操作的次数,程序应输出最后一个编号。像示例中一样,输入应为“ 1 5”,程序应打印“ 312211”。在程序中,他们只是要求编写三个函数来完成给我们的代码。
void ajouter_chiffre_droit(int& nombre, int chiffre);
void dire_chiffre(int& nombre, int repetitions_chiffre, int chiffre);
int lire_et_dire(int nombre);
他们给我们的程序部分就是这个,我们应该填写上面的三个功能:
#include <iostream>
using namespace std;
int separer_chiffre_gauche(int& nombre)
{
int dix(1);
int temp(nombre);
while (temp >= 10) {
dix *= 10;
temp /= 10;
}
nombre %= dix;
return temp;
}
/*****************************************************
* Compléter le code à partir d'ici
*****************************************************/
void ajouter_chiffre_droit(int& nombre, int chiffre)
{
}
void dire_chiffre(int& nombre, int repetitions_chiffre, int chiffre)
{
}
int lire_et_dire(int nombre)
{
}
/*******************************************
* Ne rien modifier après cette ligne.
*******************************************/
void repeter_lire_et_dire(int& nombre, int fois)
{
while (fois-- > 0) {
nombre = lire_et_dire(nombre);
}
}
int main()
{
int nombre(1);
int fois(1);
cin >> nombre >> fois;
repeter_lire_et_dire(nombre, fois);
cout << nombre << endl;
return 0;
}
我的解决方案:
void ajouter_chiffre_droit(int& nombre, int chiffre)
{
nombre *= 10 + chiffre;
}
void dire_chiffre(int& nombre, int repetitions_chiffre, int chiffre)
{
ajouter_chiffre_droit(nombre, repetitions_chiffre);
ajouter_chiffre_droit(nombre, chiffre);
}
int lire_et_dire(int nombre)
{
int nombre_temp(nombre), chiffre(0), chiffre_prec(0), rep(1), resultat(0);
chiffre_prec = separer_chiffre_gauche(nombre_temp);
do
{
chiffre = separer_chiffre_gauche(nombre_temp);
if(chiffre == chiffre_prec)
{
++rep;
}
else
{
dire_chiffre(resultat, rep, chiffre_prec);
rep = 1;
chiffre_prec=chiffre;
}
}while(nombre_temp!=0);
return resultat;
}
函数lire_et_dire
始终返回值0,我不知道为什么可以帮助我,这会很棒,谢谢!
如果您“不太可能”不理解我的问题,请阅读官方问题文本here,它是练习编号1。