这是我的学校作业。
问题陈述:
“编写一个程序来打印从1到100的素数。(素数是任何整数,只能由它自己和1均匀分配。)
要求:使用数组从1到100取数字,使用另一个数组取素数。“
这是我的代码:
#include <stdio.h>
int main ()
{
int x[100], a[100];
int y, z;
printf("here is an array going 1-100 :D\n");
for (y=2; y<=100; y++){
x[y]=y;
printf("\n%d\n", x[y]);
for (z=2; z<=y; z++){
a[z]=z;
if (a[z]%z==0){
break;
}
}
if (z==a[z]){
printf("\n%d is a prime number\n", a[z]);
}
}
return 0;
}
我有点难过。我用Google搜索了通常可以解决我问题的问题。但是,我觉得我很亲密。我相信我的第二个阵列遇到了一些麻烦。
请指导我。
答案 0 :(得分:0)
请按以下步骤找到正确答案 -
#include <stdio.h>
int main ()
{
int x[100], a[100];
int y,z;
z=0;
x[0]=1;
printf("here is an array going 1-100 :D\n");
for (y=2; y<=100; y++){
x[y-1]=y;
printf("\n%d\n", x[y-1]);
for (z=2; z<=y/2; z++){
if (a[y-1]%z==0){
break;
}
}
if (z>y/2){
printf("\n%d is a prime number\n", x[y-1]);
a[z++]=x[y-1];
}
}
return 0;
}
答案 1 :(得分:-1)
#include <stdio.h>
int main ()
{
int x[100], a[100]; //just declaring two arrays, although a[] has 100 elements i wont use them all
int y, z;//these are for the counters that will be used in the for loop
printf("here is an array going 1-100 :D\n");
for (y=2; y<=100; y++){
x[y]=y;//this will set the array to 1-100
printf("\n%d\n", x[y]);//prints out said array
for (z=2; z<=y; z++){
if (y%z==0){//prime number test
a[z]=z;//setting second array equal to prime number after it passes test
break;
}
}
if (y==z){
printf("\n%d is a prime number\n", a[z]);
}
}
return 0;
}