这个项目有什么问题吗?为什么不退出循环

What is wrong with this program? why is it not quitting the loop?

本文关键字:为什么不 退出 循环 问题 项目有 什么      更新时间:2023-10-16

所以我试图使一个程序,将确定如果数字是快乐的数字或不。但是程序似乎并没有退出循环,在输入数字之后什么也没有发生。

是我遗漏了什么还是我做错了程序?(只学习了for循环,while循环,do while循环和if语句,并且只能使用它们)

我已经做这个程序3天了,但仍然不知道这个程序有什么问题。如果你能告诉我哪里出了问题就太好了。由于

#include <iostream>
using namespace std;
int main(){
int number, temp, count;
cout<<"please enter a number :";
cin>>number; // to ask for input
while(number != 1 and number != 4)
{
    while(number !=0)
    {
        number = number/10;
        count += 1;  //start to calculate how many digits are in the number
    }
    while(count!=0)
    {
        number == number + (temp/(10^(count-1))^2); // to add the square of the number
        temp = temp%(10^(count-1));
        count-=1;
    }
    if(count == 0)
    {
        temp = number; // to set temp as number after the program is over so it can run again if it is not done
    }
}
if(number == 1){
    cout<<"This is a happy number"; // to print result
}
else if(number == 4){
    cout<<"This is not a happy number"; // to print result
}

    return 0;
}

首先正确初始化变量,计数是取一些任意值,然后用这样的垃圾值计算位数会给你一个错误的答案,而且temp变量的值也没有初始化,这也取垃圾值并使用库下CPP中的pow(x,y)函数计算一个数的幂,在CPP

中x^y不计算幂

,如果遇到任何错误,可以使用GDB进一步调试代码

正如其他一些人在评论中指出的那样,程序的逻辑是模糊的,对于您所描述的简单程序,我认为您不需要内部while循环。正如LoveTronic所指出的,回顾一些基本的循环概念可能会有所帮助。然而,为了帮助你玩一个工作程序,我修改了你的程序来做你在问题中描述的。

#include <iostream>
using namespace std;
int main() {
   int number;
   cout << "please enter a number :";
   cin >> number; // to ask for input
   while (true) {
      if ( number == 1 ) {
         cout << "This is a happy numbern";
         return 1;
      }
      else if ( number == 4 ) {
         cout << "this is not a happy numbern";
         return 1;
      }
      cout << "please enter a number :";
      cin >> number; // to ask for input
   }
   return 0; // this will never reach
}