求下面两个图片分别得的C语言代码
2个回答
展开全部
第一个程序:
#include <stdio.h>
void main()
{
int i,n;
int sum=0;
printf("Input Number:");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
sum = sum + i*i;
}
printf("sum of squares for 1 to %d = %d\n",n,sum);
}
第二个程序:
#include <stdio.h>
void main()
{
int binary_search(int *p,int j,int x);
int a[10]={1,3,5,7,9,11,13,15,17,19};
int i,t,y;
printf(" i:");
for (i=0;i<10;i++)
{
printf("%5d",i);
}
printf("\n");
printf("a[i]:");
for (i=0;i<10;i++)
{
printf("%5d",a[i]);
}
printf("\n");
printf("Search number:");
scanf("%d",&t);
y=binary_search(a,10,t);
if (-1==y)
{
printf("没有找到%d\n",t);
}
else
printf("%d is in a[%d]\n",t,y);
}
int binary_search(int *p,int j,int x)
{
int first=0;
int mid;
int last=j-1;
printf("Call to binary_search with index [%d,%d]\n",first,last);
while (first<=last)
{
mid = (first+last)/2;
if (*(p+mid)==x)
{
return mid;
}
else
{
if (x>*(p+mid))
{
first = mid+1;
printf("Call to binary_search with index [%d,%d]\n",first,last);
}
else
{
last = mid-1;
printf("Call to binary_search with index [%d,%d]\n",first,last);
}
}
}
return -1;
}
#include <stdio.h>
void main()
{
int i,n;
int sum=0;
printf("Input Number:");
scanf("%d",&n);
for (i=1;i<=n;i++)
{
sum = sum + i*i;
}
printf("sum of squares for 1 to %d = %d\n",n,sum);
}
第二个程序:
#include <stdio.h>
void main()
{
int binary_search(int *p,int j,int x);
int a[10]={1,3,5,7,9,11,13,15,17,19};
int i,t,y;
printf(" i:");
for (i=0;i<10;i++)
{
printf("%5d",i);
}
printf("\n");
printf("a[i]:");
for (i=0;i<10;i++)
{
printf("%5d",a[i]);
}
printf("\n");
printf("Search number:");
scanf("%d",&t);
y=binary_search(a,10,t);
if (-1==y)
{
printf("没有找到%d\n",t);
}
else
printf("%d is in a[%d]\n",t,y);
}
int binary_search(int *p,int j,int x)
{
int first=0;
int mid;
int last=j-1;
printf("Call to binary_search with index [%d,%d]\n",first,last);
while (first<=last)
{
mid = (first+last)/2;
if (*(p+mid)==x)
{
return mid;
}
else
{
if (x>*(p+mid))
{
first = mid+1;
printf("Call to binary_search with index [%d,%d]\n",first,last);
}
else
{
last = mid-1;
printf("Call to binary_search with index [%d,%d]\n",first,last);
}
}
}
return -1;
}
展开全部
//第一个图
int main(){
int input = 0;
int sum = 0;
int i = 1;
printf("Input number:");
scanf("%d", &input);
for(;i <= input; i++){
sum += i*i;
}
printf("sum of squares from 1 to %d = %d", input, sum);
}
//第二个图
int main(){
int a[10] = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19};
//这里我就没有循环赋值,一共也就是10个数字,如果需要用循环的话,也就是上一个
//数字+2
int i = 0;
int input = 0;
//输出第一行i
printf("i : ")
for(; i < 10; i++){
printf("%d\t", i);
}
printf("\n");
//输出第二行a[i]
printf("a[i] : ")
for(i = 0; i < 10; i++){
printf("%d\t", a[i]);
}
printf("\n");
printf("Search number: ");
scanf("%d", &input);
//这是二分查找法,具体算法我懒得写了……你自己看一下吧,不过我觉得这个查找的顺序有点奇怪
}
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询