gpt4 book ai didi

C++在while循环中更改变量

转载 作者:太空狗 更新时间:2023-10-29 23:17:18 25 4
gpt4 key购买 nike

我是 C++ 的新手,正在尝试完成 [Project Euler][1]。我一路走到了 [问题 4][2](我知道这令人印象深刻)并且我在 while 循环中遇到了我认为我的变量范围的问题。如果你不知道,这道题要求你找出两个三位数整数的最高回文积。我制作了一个 while 循环,应该 测试产品是否为回文(我将其放入另一个函数 - 工作正常)。

这是我当前的代码(虽然它已经更改了很多次 - 我试图使这个代码最明确,这就是为什么所有其他 ifs):

int main()
{

int int1 = 999;
int int2 = 999;
int nProduct = int1 * int2;
int nFinalProduct = 0;

while (int1 >= 100)
{
if (paltest(nProduct) == 1 && nProduct > nFinalProduct && int2 > 100)
{
nFinalProduct = nProduct;
--int2;
}
else if (paltest(nProduct) == 1 && nProduct > nFinalProduct
&& int2 == 100)
{
nFinalProduct = nProduct;
--int1;
}
else if (paltest(nProduct) == 0 && int2 > 100)
{
--int2;
}
else if (paltest(nProduct) == 0 && int2 == 100)
{
--int1;
}
}
cout << nFinalProduct;
}

我主要是想判断该乘积是否为回文且高于前一个,将其添加到 nFinalProduct,然后递减 int1 或 int2 以获得下一个乘积。

我尝试使用相同类型的逻辑多次重写 main(),但每次输出都没有从我初始化的 nFinalProduct 更改为(在本例中为 0)。它是否只更新 while 循环内的值,然后在循环结束后重置它?我对 Project Euler 的第三个问题的解决方案使用了初始化变量的相同想法,在 while 循环内更改它并在循环外打印它,效果很好。我想不出这里的问题是什么,除非它永远不会发现 paltest() 为 1,我已经测试了堆但找不到问题。

感谢任何帮助。

更新:好的,伙计们,谢谢。我将 nProduct 声明移到 while 循环内,现在它不会结束。这是我的新代码:

int main(){

int int1 = 999;
int int2 = 999;
int nFinalProduct = 0;

while (int1 >= 100){

int nProduct = int1 * int2;

if (paltest(nProduct) == 1 && nProduct > nFinalProduct && int2 > 100){
nFinalProduct = nProduct;
--int2;
}
else if (paltest(nProduct) == 1 && nProduct > nFinalProduct && int2 == 100){
nFinalProduct = nProduct;
int2 = 999;
--int1;
}
else if (paltest(nProduct) == 0 && int2 > 100){
--int2;
}
else if (paltest(nProduct) == 0 && int2 == 100){
int2 = 999;
--int1;
}
}
cout << nFinalProduct;
}

现在将无限期运行。我的感觉是 int1 永远不会递减(这最终会终止循环)。如果它没有被递减,则意味着 int2 永远不会递减。我走在正确的轨道上吗?

[1] https://projecteuler.net[2] https://projecteuler.net/problem=4

最佳答案

如果我对问题的理解正确,您希望在循环的每次迭代中更新“nProduct”。所以唯一的改变是把'nProduct = int1 * int2;'就在“while (int1 >= 100){”下方。

关于C++在while循环中更改变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18709851/

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