使用C ++

时间:2017-10-02 02:20:57

标签: c++

我有一个作业,用于填写以下函数(detectHappy)的正文,该函数将检查数字是否为幸福数字,为期10个周期 (迭代)只。我必须:

- 找到数字的总和。

- 检查在第1点中获得的结果。如果为1,则将值1赋值给变量' finalNumber',否则再次执行第1点,直到获得的数字为1或直到循环数为止增加到10。

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

我不应该输入,输出或声明任何其他功能。我只需要编写已经在那里声明的函数的主体,这将使它在我的课程中提供的shell上运行...

我试图编写的程序编译但没有给出正确的结果。我现在缺乏想法,我将不胜感激任何帮助。提前谢谢。

代码:

/*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);

}

3 个答案:

答案 0 :(得分:0)

摆脱do while循环并添加for循环

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

{

`Code stuff`

}

答案 1 :(得分:0)

您的代码充满了错误。阅读以下代码中的注释

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
}

答案 2 :(得分:0)

现在使用这种方法做到了......

/ *问题:编写代码以查找数字是否为满意数字(最多10个周期)。

int number:确定是否满意的数字

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

int cycle_no:存储完成的迭代次数以确定是否 '号码'很高兴* /

void detectHappy(int number,int&amp; finalNumber,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;

}

}