if嵌套(判断小猪体重)
#include<iostream> using namespace std; int main() { //三只小猪称体重,判断那只最重 //1.创建三只小猪的体重 int num1 = 0; int num2 = 0; int num3 = 0; //2.输入体重 cout << "请输入小猪A的体重" << endl; cin >> num1; cout << "请输入小猪B的体重" << endl; cin >> num2; cout << "请输入小猪C的体重" << endl; cin >> num3; cout << "小猪A的体重为:" << num1 << endl; cout << "小猪B的体重为:" << num2 << endl; cout << "小猪C的体重为:" << num3 << endl; //3.判断那只猪最重 if (num1 > num2) { if (num1 > num3) { cout << "小猪A最重" << endl; } else { cout << "小猪C最重" << endl; } } else { if (num2 > num3) { cout << "小猪B最重" << endl; } else { cout << "小猪C最重" << endl; } } system("pause"); return 0; }
while循环(猜数字)
#include<iostream> using namespace std; #include<ctime> int main() { //添加随机数种子 利用当前系统时间生成随机数,防止每次随机数都一样 srand((unsigned int)time(NULL)); //系统生成随机数 int num = rand() % 100 + 1; cout << num << endl; //玩家输入猜测数据 int val = 0; while (1) { cin >> val; //判断玩家的猜测 if (val > num) { cout << "猜测过大" << endl; } else if (val < num) { cout << "猜测过小" << endl; } else { cout << "恭喜您猜对了" << endl; break;//跳出循环 } } system("pause"); return 0; }
一维数组(五只小猪称体重)
#include<iostream> using namespace std; #include<ctime> int main() { //创建5只小猪体重的数组 int arr[5] = { 300,350,200,400,250 }; //从数组中找到最大值 int max = 0; for (int i = 0; i < 5; i++) { if (arr[i] > max) { max = arr[i]; } } //打印最大值 cout << "最重的小猪体重为: " << max << endl; system("pause"); return 0; }
一维数组(元素逆置)
#include<iostream> using namespace std; #include<ctime> int main() { //实现数组元素逆置 //创建数组 int arr[5] = { 1,3,2,5,4 }; cout << "数组逆置前:" << endl; for (int i = 0; i < 5; i++) { cout << arr[i] << endl; } //实现逆置 //记录起始下标的位置 //记录结束下标的位置 //起始下标与结束下标的元素互换 //起始位置++,结束位置-- //循环执行操作,直到起始位置>+结束位置 int start = 0; int end = sizeof(arr) / sizeof(arr[0] - 1); while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++; end--; } cout << "数组元素逆置后:" << endl; for (int i = 0; i < 5; i++) { cout << arr[i] << endl; } system("pause"); return 0; }
一维数组(冒泡排序)
#include<iostream> using namespace std; #include<ctime> int main() { //冒泡排序: //1.比较相邻的元素,如果第一个比第二个大,就交换他们两个 //2.对每一对相邻元素做同样的工作,执行完毕后,找第一次的排序后的最大值 //3.重复以上步骤,每次比较次数-1,直到不需要比较 //利用冒泡排序实现升序序列 int arr[9] = { 4,2,8,0,5,7,1,3,9 }; cout << "排序前:" << endl; for (int i = 0; i < 9; i++) { cout << arr[i] << " "; } cout << endl; //排序总轮数 = 元素个数 - 1; //每轮对比次数 = 元素个数 - 排序轮数 -1 ; //开始冒泡排序 //排序总轮数 = 元素个数 - 1; for (int i = 0; i < 9 - 1; i++) { //内层循环对比次数 = 元素个数 - 排序轮数 -1 ; for (int j = 0; j < 9 - i - 1;j++) { //如果第一个数字比第二个数字大,交换两数字 if (arr[j] > arr[j + 1]) { int temp = arr[j]; arr[j] = arr[j + 1]; arr[j + 1] = temp; } } } cout << "排序后:" << endl; for (int i = 0; i < 9; i++) { cout << arr[i] << " "; } cout << endl; system("pause"); return 0; }
原文:https://www.cnblogs.com/wwisgodss/p/13492482.html