[英]C programming , array not printing properly
So for class we are doing some encryption/ decryption algorithms with prime numbers. 因此,对于类,我们正在使用质数进行一些加密/解密算法。 I am in the first part of making the program. 我正在编写程序的第一部分。 I am trying to get the program to check if a number is prime or not. 我正在尝试让程序检查数字是否为质数。 After this, I want the program to store all prime numbers before that number in an array called prime_array. 之后,我希望程序将所有在该数字之前的质数存储在称为prime_array的数组中。 And I was trying to get those results to print out on the screen. 我试图将这些结果打印在屏幕上。 It's not working the way I intended. 它没有按照我的意图工作。 I'm later going to use this in decryption of something a bit more complex. 稍后,我将在解密更复杂的内容时使用它。 Just wandering if anyone could see what part of my code is causing the issues. 只是在徘徊,如果有人可以看到我的代码的哪一部分导致了问题。
Code: 码:
#include <stdio.h>
int main()
{
int n;
int prime;
int prime_array[1000];
int prime_answer;
int j=0;
printf("enter a number for n : ");
scanf_s("%d", &n);
if (n % 2 == 1)
{
printf("Number is prime.");
getchar();
getchar();
for (int i = 0; i <= n; i++)
{
if (n - 1 % 2 == 1)
{
n--;
prime_array[j] = n;
j++;
}
else
{
// do nothing
}
}
}
else if (n % 2 == 0)
{
printf("Number is not prime.");
getchar();
getchar();
}
for (int k = 0; k<= 10; k++)
{
printf("\n\n %d",prime_array[k]);
if (k == 10);
{
getchar();
getchar();
}
}
}
Problem is this condition- 问题是这种情况-
if (n - 1 % 2 == 1)
This exression is treated as (n-(1 % 2))==1
, because %
has higher precedence than -
,therefore , 1 % 2
is evaluated first .As 1 % 2
is 1
and expression become n-1
,so condition will not be true
until n
is 2
( not as you would desire ) . 此表达式被视为(n-(1 % 2))==1
,因为%
优先级高于-
,因此,首先对1 % 2
求值。由于1 % 2
为1
且表达式变为n-1
,因此条件直到n
为2
( 并非如您所愿 )才会是true
。
You need to write like this - 您需要这样写-
if ((n - 1) % 2 == 1)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.