如何消除while重复cout
Requires: start > 0; end > 0; 0 <= digit <= 9
//Modifies: nothing
//Effects: runs the range of numbers from start to end inclusive
// if (end < start), it will swap start and end
// prints the number if any digit of the number is the
// same as 'digit'
// printIfHoldsDigit(5, 10, 7) //prints: 7
// printIfHoldsDigit(5, 30, 8) //prints: 8, 18, 28
// printIfHoldsDigit(1, 30, 2) prints: 2, 12, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29
// and yes you need to print the commas
以上是function的要求
以下是我的code,现在有的问题是如果运行(1,30,2),22会出现两次,不知道有什么办法可以消除这个问题?初学的在此谢过了!!!
如果发帖格式有问题也请见谅,新人一枚= =
void printIfHoldsDigit(int start, int end, int digit){ int s=start; int e=end; if(s>e) { s=end; e=start; } while(s<=e) { int temp=s; while(temp>0) { if(temp%10==digit) { if(e<=10) { cout <<s; } else if(10<e&&e<=digit*10) { if(e/10==(temp+10)/10) { cout <<s; } else { cout <<s<<", "; } } else if(e>digit*10) { if(s+1==e) { cout <<s; } else { cout <<s<<", "; } } } temp=temp/10; } s=s+1; }}/* 因为22这个情况比较特殊, 你的循环执行了两次,22%10==2执行一次, 22/10后为2%10又等于2再执行一次 */#include <iostream>using std::cout;void printIfHoldsDigit(int start, int end, int digit){ int s=start; int e=end; if(s>e) { s=end; e=start; } while(s<=e) { int temp=s; int nFlag = 0; //加个标志 while(temp>0) { if(!nFlag && temp%10==digit) //加个标志判断 { nFlag = 1; //加个标志赋值 if(e<=10) { cout <<s; } else if(10<e&&e<=digit*10) { if(e/10==(temp+10)/10) { cout <<s; } else { cout <<s<<", "; } } else if(e>digit*10) { if(s+1==e) { cout <<s; } else { cout <<s<<", "; } } } temp=temp/10; } s=s+1; }}int main(void){ printIfHoldsDigit(5, 10, 8); return 0;}