这个项目有什么问题吗?为什么不退出循环
What is wrong with this program? why is it not quitting the loop?
所以我试图使一个程序,将确定如果数字是快乐的数字或不。但是程序似乎并没有退出循环,在输入数字之后什么也没有发生。
是我遗漏了什么还是我做错了程序?(只学习了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
}
相关文章:
- 为什么不;名字在地图上是按顺序排列的吗
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 为什么异常不退出程序?
- 为什么不调用移动构造函数?(默认情况下只有构造器,没有别的)
- C++ 基本 CTOR 说明 - 为什么不调用赋值/复制构造函数
- 为什么不递增?(构造函数)
- 为什么不允许成员函数和非成员函数之间的函数重载?
- 为什么不允许使用可变长度数组作为向量元素?
- 虽然循环在使用回车键时不退出程序
- C++:为什么不调用移动构造函数?
- 在 C++ 中声明 const 对象需要用户定义的默认构造函数.如果我有一个可变成员变量,为什么不呢?
- 为什么不能用常量表达式声明数组?
- 为什么不能直接引用作用域枚举类成员,而不能为无作用域枚举生成类成员?
- C++ queue.front();为什么不从第一个元素开始呢?
- 为什么不允许这种交叉广播?
- 为什么循环退出不会?
- 这个项目有什么问题吗?为什么不退出循环
- 为什么我的代码不退出时,在命令提示符中输入3
- 我的旧Qt项目文件(.pro文件),它正在工作;不创建任何文件(moc_ 或 .obj 文件)。为什么它退出构建步骤什么都不做?
- 为什么 gdb "u" 命令不退出循环?