0

## 想請教C語言的問題

1.使用while撰寫一個程式，當輸入一個0~9之間的整數時，印出所有小於等於100這個整數的倍數。
8 16 24 32 40 48 56 64 72 80 88 96

2.使用for撰寫一個程式，可以算出全班平均成績至小數第二位，第一個輸入總共要計算

50 90 80 70 60
The average is 70.00

3.請撰寫一個終極密碼程式，遊戲關主先輸入一個0~100之間的整數作為終極密碼，接著玩遊戲的人一直輸入0~100之間的整數，直到猜對為止，若輸入超出範圍的數字必需要求使用者重新輸入，使用者每輸出一個數字必需提醒使用者此終極密碼比輸入的數字大還是小。螢幕輸出如下:
Please enter a target number: 45
Please enter a guessing number : 50
The target number is less than the guessed number
Please enter a guessing number : -10
Error guessing number!
Please enter a guessing number : 40
The target number is greater than the guessed number
Please enter a guessing number : 45
Congratulation! You got it.

#include <stdio.h>

int main() {
int t = 1;
while(i<=100)
{
if((i%t)==0)
printf("%d",t);
i+=t;
}
return 0;
}

KYCPG iT邦新手 4 級 ‧ 2020-08-13 18:07:26 檢舉

wrxue iT邦研究生 4 級 ‧ 2020-08-13 18:55:21 檢舉

### 1 個回答

2

iT邦新手 3 級 ‧ 2020-08-14 04:56:57

(很重要嗎 @@?直接給code >w<)

``````#include <iostream>

using namespace std;

int main()
{
int n;
cout<<"Please enter a number 0-9 :\n";
cin >> n;
for(int i=1;i <= n;i++){             //用for會從1開始的特性
cout<< i*i <<" ";                //平方
}
return 0;
}
``````

``````#include <iostream>

using namespace std;

int main()
{
int a, b, i = 0, sum=0;     //連續宣告 使用while前皆須宣告其條件變數
cin >> a;
while(i < a){               //用while使i不為區域變數，就不用多寫一個計數器
i++;                    //你管我寫在前面還後面
cin >> b;
sum = sum + b;          //輸入後，丟進sum存入b的值
}
cout << "The average is " << sum/i;
}
``````

``````#include <iostream>

using namespace std;

int main()
{
int target, guessed;
cout << "Please enter a target number : ";
cin >> target;
while(1) {
cout << "Please enter a guessed number : ";
cin >> guessed;
if(guessed<0 or guessed>100) {
cout << "The number you guessed is invalid!\n";
}
else {
if(target < guessed) {
cout << "The target number is lower than the guessed number\n";
}
else if(target > guessed) {
cout << "The target number is higher than the guessed number\n";
}
else {
cout << "Congratulation! You got it.";
return 0;
}
}
}

}
``````