gpt4 book ai didi

c++ - 我的循环不会循环

转载 作者:行者123 更新时间:2023-11-28 01:52:42 25 4
gpt4 key购买 nike

我有一个作业,我们必须编写代码来找到适合四个参数的数字。我的想法是将该数字拆分成各个数字,然后使用 if 语句检查该数字是否符合参数。如果不是,我希望它增加一个并循环直到找到数字。然而,我的循环只运行一次,甚至不返回所有四位数字。任何关于我应该做什么的指示都将不胜感激。

#include <iostream>
using namespace std;
int digit_breakdown(int& number);
int main()
{

int number = 1000; //This is the variable I will change to find the secret number
int last_dig, third_dig, sec_dig, first_dig; // These are variables that represent each of the four digits
int secret_number = 0; //This variable holds the secret number

do{
number++;
last_dig = number%10; //This series of code breaks up the number into digits
number /= 10;
third_dig = number%10;
number /= 10;
sec_dig = number%10;
number /= 10;
first_dig = number%10;
number /=10;

if((first_dig != sec_dig) && (first_dig != third_dig) && (first_dig != last_dig) && (sec_dig != third_dig) && (sec_dig != last$
number = secret_number;
}while((secret_number = 0));

cout << "You found the secret number! That number is " << secret_number;
cout << last_dig << endl;
cout << third_dig << endl;
cout << sec_dig << endl;
cout << first_dig << endl;

}

最佳答案

我已经根据给出的有问题的陈述更改了逻辑和一些陈述。即使您将按照建议更改 while 循环条件,您也不会获得准确的输出。

所以变化是。

A) secret_number 在循环开始时分配并保存递增的数字

B) 对secret_number变量进行修改操作

C) 一旦满足条件就使用“break”。(因为你得到了你的密码)

E) 因为您的条件是无穷无尽的,直到您找到所需的数字,将循环更改为 while(1) [这是可选的,您可以将其设置为某个上限]

F) 显示数字本身。

下面是代码细节。

#include <iostream>
using namespace std;
int digit_breakdown(int& number);
int main()
{

int number = 1000; //This is the variable I will change to find the secret number
int last_dig, third_dig, sec_dig, first_dig; // These are variables that represent each of the four digits
int secret_number = 0; //This variable holds the secret number

do{
secret_number = ++number;
last_dig = secret_number%10; //This series of code breaks up the number into digits
secret_number /= 10;
third_dig = secret_number%10;
secret_number /= 10;
sec_dig = secret_number%10;
secret_number /= 10;
first_dig = secret_number%10;
secret_number /=10;

if((first_dig != sec_dig) && (first_dig != third_dig) && (first_dig != last_dig) && (sec_dig != third_dig) && (sec_dig != last_dig)){
break;
}
}while(1); //To avoid endless loop you can set some upper_limit

cout << "You found the secret number! That number is " << number<<endl;
cout << last_dig << endl;
cout << third_dig << endl;
cout << sec_dig << endl;
cout << first_dig << endl;

return 0;
}

输出如下:

/WorkDir/checks/stackover> vi loop_digit.cpp
/WorkDir/checks/stackover> g++ -Wall -Wextra -O2 -o loop_digit loop_digit.cpp
/WorkDir/checks/stackover> ./loop_digit
You found the secret number! That number is 1022
2
2
0
1

关于c++ - 我的循环不会循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42335032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com