帮我看看这两道题哪里有问题吧,谢谢了。
这是计算high以内最大的10个素数之和的代码,能执行:问题是照理来说输入10输出应该是17,可它为什么是21???程序代码:
# include <stdio.h> # include <math.h> int fun(int high) { int sum=0, i, n=0, yes; while ((high>=2) && (n<=10)) { yes = 1; for (i=2; i<high/2; i++) if(high%i == 0) { yes=0; break; } if(yes) { sum += high; n++; } high--; } return sum; } int main(void) { int high, sum; printf("请输入high的值:"); scanf("%d", &high); sum = fun(high); printf("%d\n", sum); return 0; }
这道题是把前半部分元素的值与后半部分元素的值对换,如果是奇数个,则中间的数保持不变。
如1,2,3,4,5,6,7,8,9变换后就成了,6,7,8,9,5,1,2,3,4
问题是编译组建都没有错误,可就是执行错误……代码如下:
程序代码:
# include <stdio.h> # define N 9 void fun(int a[], int n) { int i, t, p; p = (n%2==0)?(n/2):(n/2+1); for (i=0; i<p; i++) { t = a[i]; a[i] = a[p+i]; a[p+i] = t; } } int main(void) { int b[N] = {1, 2, 3, 4, 5, 6, 7, 8, 9}; int i; printf("\nThe original data :\n"); for (i=0; i<N; i++) printf("%4d", b[i]); printf("\n"); fun(b, N); printf("\nThe data after moving :\n"); for (i=0; i<N; i++) printf("%4d", b[i]); printf("\n"); return 0; }
[ 本帖最后由 ai8343512 于 2011-8-28 16:50 编辑 ]