gpt4 book ai didi

c++ - 变量作用域大于for循环,为什么不改变值?

转载 作者:行者123 更新时间:2023-11-27 23:01:10 26 4
gpt4 key购买 nike

我有以下代码:

void nLargestPalindrome(double number){
int i = 5; //subtract "1" because array starts at zero
int intermediate = i; //intermediate value - equal to the array index;
double *decimalDigit = new double[i + 1];
while (0 <= i){ //acquire digits of number
decimalDigit[i] = (number - fmod(number, pow(10, i))) / pow(10, i);
cout << "Value of digit place " << i << " is " << decimalDigit[i] << endl;
number = fmod(number, pow(10, i));
i--;
}

所以我初始化了一个数组,其值等于它所在的数字位置,即 979979 ---> dD[5] = 9,dD[4] = 7,等等...

现在我在同一个函数中有以下代码:

double numberVectorAddition = pow(10, 5)*decimalDigit[0] + pow(10, 4)*decimalDigit[1] + pow(10, 3)*decimalDigit[2] + pow(10, 2)*decimalDigit[3] + pow(10, 1)*decimalDigit[4] + decimalDigit[5];
for (int q = 0; q < 10; q++){ //decreases size of palindrome to the next largest palindrome.
cout << decimalDigit[0] << decimalDigit[1] << decimalDigit[2] << decimalDigit[3] << decimalDigit[4] << decimalDigit[5] << '\t';
cout << numberVectorAddition << endl;
decimalDigit[2]--;
decimalDigit[3]--;
if (decimalDigit[2] == 0){
cout << decimalDigit[0] << decimalDigit[1] << decimalDigit[2] << decimalDigit[3] << decimalDigit[4] << decimalDigit[5] << '\t';
cout << numberVectorAddition << endl; //runtime error??
...
}
}

number = 997799

时我得到以下输出
Value of digit place 5 is 9
Value of digit place 4 is 9
Value of digit place 3 is 7
Value of digit place 2 is 7
Value of digit place 1 is 9
Value of digit place 0 is 9
997799 997799
996699 997799
995599 997799
994499 997799
993399 997799
992299 997799
991199 997799
990099 997799
989989 997799
988889 997799
987789 997799

什么给了?我真诚地尝试在谷歌中四处寻找 30 分钟,因为我之前在这里遇到过一系列低质量的问题。但是我没有成功。

我的问题:因为 numberVectorAddition 大于 for 循环范围,nVA 的值不应该改变吗?

最佳答案

线

double numberVectorAddition = pow(10, 5)*decimalDigit[0] + pow(10, 4)*decimalDigit[1] + pow(10, 3)*decimalDigit[2] + pow(10, 2)*decimalDigit[3] + pow(10, 1)*decimalDigit[4] + decimalDigit[5];

需要放在for循环中。

    for (int q = 0; q < 10; q++){ //decreases size of palindrome to the next largest palindrome.
double numberVectorAddition = pow(10, 5)*decimalDigit[0] + pow(10, 4)*decimalDigit[1] + pow(10, 3)*decimalDigit[2] + pow(10, 2)*decimalDigit[3] + pow(10, 1)*decimalDigit[4] + decimalDigit[5];
cout << decimalDigit[0] << decimalDigit[1] << decimalDigit[2] << decimalDigit[3] << decimalDigit[4] << decimalDigit[5] << '\t';
cout << numberVectorAddition << endl;
decimalDigit[2]--;
decimalDigit[3]--;
if (decimalDigit[2] == 0){
cout << decimalDigit[0] << decimalDigit[1] << decimalDigit[2] << decimalDigit[3] << decimalDigit[4] << decimalDigit[5] << '\t';
cout << numberVectorAddition << endl; //runtime error??
...
}

否则,它会被计算一次并保持在该值。

关于c++ - 变量作用域大于for循环,为什么不改变值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27513460/

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