我有以下代码:
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 ---&gt; 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的值是否应该更改?
答案 0 :(得分:4)
该行
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??
...
}
否则,计算一次并保持该值。
答案 1 :(得分:0)
numberVectorAddition
本身都不会神奇地改变。一旦numberVectorAddition
得到它的值,那就是你分配给它...在这段代码中,你永远不会这样做!