具有C 的迭代解决方案

Iterative solutions with C++

本文关键字:解决方案 迭代 具有      更新时间:2023-10-16

我有一个任务填写以下功能的正文(检测),该功能将检查一个数字是否是一个快乐的数字,对于10个周期(迭代)。我必须:

- 查看数字的数字之和。

- 检查点1中获得的结果。如果是1,则将值1分配给变量" finalnumber",否则再次执行点1,直到获得的数字为1或直到周期数量增加到10。<<<<<</p>

- 将迭代值分配给变量'cycle_no'。

我不应该输入,输出或声明任何其他功能。我只需要写出已经声明的功能的主体,这会使它在我的课程中提供的外壳上工作...

我试图编写编译但没有给出正确的结果的程序。我现在没有想法,我将感谢任何帮助。预先感谢您。

代码:

/*Question      : Write your code to find whether the number is a happy 
number or not (for max 10 cycles).
int number      : The number to be determined whether it is happy or not
int finalNumber : Store the resultant value in this variable
int cycle_no    : Store the number of iterations done to determine whether 
the 'number' is happy or not */

void detectHappy(int number, int &finalNumber, int &cycle_no) {
//Write your solution code below this line

int sum = 0;
int i = 0;
do{
    sum += (number%10)*(number%10);
    number /=10;

    if (sum == 1){
        finalNumber = 1;
        break;
    }
    else {
        number = sum;
        i++;
    }
    cycle_no = i;

}
while (i < 10);

}

循环时摆脱do,添加一个循环

int i; for (i=0; i <10; i++)

{

`Code stuff`

}

您的代码到处都是错误。在以下代码中阅读评论

void detectHappy(int number, int &finalNumber, int &cycle_no) {
    //Write your solution code below this line
    int r,   sum = 0; // Are you sure you need to declare r variable in here?!! You are modifying this variable inside the do-while(). 
    int i = 1; // where do you increment this value in your code?!!
   do { // the choice of do-while is fine in here because any integer number must have at least one digit. 
       r = number%10;
       sum += r*r; // Is this correct? 
       number = number/10;
       if (sum == 1){
           finalNumber = 1;
           break;
       } // there is an else statement in here. Read the instructions carefully. 

       if (sum !=1 || i != 10){ //  ( i != 10 ) this is always TRUE. You are not incrementing i in your code!!
            r = number%10;
            sum += r*r; // Is this correct? 
            number = number/10;
            number = sum;
       }
       cycle_no = sum; // Are you sure?!! cycle_no is iteration number NOT the sum. 
                       // Read this carefully: Assign the iteration value to the variable 'cycle_no'.
   }
   // this while is always true. It has no meaning in this sense. 
   while (10); //I want it to iterate successively for a maximum of 10 times if the lucky number is not found
}

现在使用此方法...

/*问题:编写您的代码以查找数字是否是一个快乐的数字(对于最大10个周期)。

int编号:要确定是否快乐的数字

int farmnumber:将结果值存储在此变量

int cycle_no:存储已完成的迭代次数以确定是否是否"数字"是快乐的 */

void dentecthappy(int number,int&amp; partnumber,int&amp; cycle_no){

>
//My code
 for (cycle_no=0; cycle_no < 10; cycle_no ++)

{

finalNumber = 0;
while (number)
{
  finalNumber += (number % 10)  * (number % 10);
  number /= 10;
}
if (finalNumber == 1)
  return;
number = finalNumber;

}

}