分析:設有a,b,c三個變量,可以用於控制三位數的個位(c),十位(b*10),百位(a*100),使用for循環嵌套,分別控制個位、十位、百位的切換,遇到符合條件的數便輸出,定義變量count用於計數,每輸出一個數便加一
代碼如下:
#include <stdio.h>
int main(void) {
//輸出符合條件的數
int a, b, c;
int number = 0;
int count = 0;
for (a = 1; a < 5 ; a++) { //控制百位
for ( b = 1 ; b < 5; b++) { //控制十位
for( c = 1 ; c < 5 ; c++){ //控制個位
number = 100 * a + 10 * b + c;
if (a!=b && a!=c && b!=c ) { //排除重複的數字
printf("%4d",number);
count++;
}
}
}
}
//輸出個數
printf("一共有%d個數\n", count);
return 0 ;
}
在執行此程序時,一共進行了4*4*4=64個循環,實際上其中有40個循環是沒必要全部執行的,爲了提高代碼運行效率,可以使用continue語句優化
代碼如下:
#include <stdio.h>
int main(void) {
//輸出符合條件的數
int a, b, c;
int number = 0;
int count = 0;
for (a = 1; a < 5 ; a++) {
for (b = 1; b < 5; b++) {
if (a == b) { //當a=b時不需要再執行下面的語句
continue;
}
for (c = 1; c < 5; c++) {
if (a == c || b == c) { //當a=c或b=c時不需要再執行下面的語句
continue;
}
number = a*100+b*10+c;
printf("%4d",number);
count++;
}
}
}
//輸出個數
printf("一共有%d個數\n",count);
return 0;
}