学习C语言第四天(循环语句练习题)
//3月1号 学习笔记
#include <stdio.h>
//找10个有序数值的某一个数值的下标
//折中法 & 二分法
int main() {
int arr[] = { 1,2,3,4,5,6,7,8,9,10 };
int x = 7;
int sz = sizeof(arr) / sizeof(arr[0]);// 计算元素个数
int left = 0; //左下标
int right = sz - 1; //右下标
while (left<=right) {
int mid = (left + right) / 2;
if (arr[mid] > x) {
right = mid - 1;
}
else if (arr[mid] < x) {
left = mid + 1;
}else {
printf("找到了,下标是%d\n", mid);
break;
}
}
if (left > right) {
printf("找不到!\n");
}
return 0;
}
// 求10个数的阶乘的和
// 方法一
//int main() {
//int i = 0;
//int n = 0;
//int ret = 1;
//int sum = 0;
//for (n = 1; n <= 10;n++){
//ret = ret * n;
//sum = sum + ret;
//}
//printf("sum= %d\n", sum);
//return 0;
//}
// 求10个数的阶乘的和
//方法二
//int main() {
//int i = 0;
//int n = 0;
//int ret = 1;
//int sum = 0;
//for (n = 1; n <= 10;n++) {
//ret = 1;
//for (i = 1; i <= n; i++) {
//ret = ret * i;
//}
//sum = sum + ret;
//}
//printf("sum= %d\n", sum);
//return 0;
//}