1.在程序中定义一个int型变量,赋予1~100的值,要求用户猜这个数,比较两个数的大小,把结果提示给用户,直到猜对位置,分别使用while和do……while来实现。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
| 用while实现 */ #include<iostream> using namespace std; int main() { int n,m; cout << "请出题者输入一个数(1~100): "; cin >> n; cout << "请猜题者输入数字(1~100):"; while (!cin.fail()) { cin.clear(); cin.sync(); cin >> m; if (m < n) { cout << "输入数字比既定数字小,请重新输入:"; continue; } else if (m > n) { cout << "输入数字比既定数字大,请重新输入:"; continue; } else { cout << "恭喜你猜对了数字,记得找铎神领取红包!" << endl; break; } } system("pause"); return 0; } 用do……while实现 */ #include<iostream> using namespace std; int main() { int n, m; cout << "请出题者输入一个数(1~100): "; cin >> n; cout << "请猜题者输入数字(1~100):"; do{ cin.clear(); cin.sync(); cin >> m; if (m < n) { cout << "输入数字比既定数字小,请重新输入:"; continue; } else if (m > n) { cout << "输入数字比既定数字大,请重新输入:"; continue; } else { cout << "恭喜你猜对了数字,记得找铎神领取红包!" << endl; break; } } while (!cin.fail()); getchar(); getchar(); return 0; }
|
2.输出九九乘法表
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| #include<iostream> #include<iomanip> using namespace std; int main() { for (int i = 1; i <= 9; i++) { for (int j = 1; j <= 9; j++) { cout << i << "*" << j << "=" << setw(2) << i*j << " "; } cout << endl; } system("pause"); return 0; }
|
3.完成函数,参数为两个unsigned short int型数,返回值为第一个参数除以第二个参数的结果,数据类型为short int;如果第二个参数为0,则返回值为-1,在主程序中实现输入输出。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| #include<iostream> using namespace std; short int transfun(unsigned short int n1 , unsigned short int n2); int main() { unsigned short int n1, n2; cout << "请输入第一个数:"; cin >> n1; cout << "请输入第二个数:"; cin >> n2; cout<<"返回值是"<<transfun(n1, n2)<<endl; system("pause"); return 0; } short int transfun(unsigned short int n1, unsigned short int n2) { if (n2 == 0) { return -1; } else { return n1 / n2; } }
|
4.编写函数把华氏温度转成摄氏温度
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| #include<iostream> using namespace std; void CelTransFah(double Fah); int main() { double Fah; while (!cin.fail()) { cin.clear(); cin.sync(); cout << "请输入一个华氏温度:"; cin >> Fah; CelTransFah(Fah); } system("pause"); return 0; } void CelTransFah(double Fah) { double Cel; Cel = (Fah - 32.0)*5.0 / 9.0; cout << "相应的摄氏温度为:" << Cel << "°C" << endl; }
|