代码运行良好,但是为什么我在int结果中的答案是错误的?
在输出中:
3
10
2 3 5 7: 17 //correct
30
2 3 5 7 11 13 17 19 23 29: 146 //incorrect
50
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47: 474 //incorrect代码如下:
#include <stdio.h>
int main() {
int y, n, i, fact, j, result = 0;
scanf("%d", &y);
for (int x = 1; x <= y; x++) {
scanf("%d", &n);
for (i = 1; i <= n; i++) {
fact = 0;
for (j = 1; j <= n; j++) {
if (i % j == 0)
fact++;
}
if (fact == 2) {
result += i;
printf("%d ", i);
}
}
printf(": %d\n", result); //Not Getting correct answer please HELP!
}
return 0;
}发布于 2021-02-05 02:11:12
您忘记在每次计算之前初始化result。
for(int x=1;x<=y;x++){
scanf("%d", &n);
result = 0; // add this for initialization
for (i = 1; i <= n; i++) {
/* ... */
}
/* ... */
}发布于 2021-02-05 02:22:27
变量result仅初始化一次
int y, n, i, fact, j, result = 0;因此,它将累加在循环中计算的值
for(int x=1;x<=y;x++){
//...
}在循环体中移动变量result的声明
for(int x=1;x<=y;x++){
int result = 0;
//...
}为了避免这样的错误,您应该在使用变量的最小范围内声明变量。
还有这个循环
for (j = 1; j <= n; j++)
{
if (i % j == 0)
fact++;
}不是很有意义。按以下方式更改循环中的条件
for (j = 1; j <= i; j++)
{
if (i % j == 0)
fact++;
}用变量i替换变量n。
此外,您应该使用无符号整数类型,而不是有符号整数类型int,因为素数是为自然数定义的。
例如,该程序可以通过以下方式进行查看
#include <stdio.h>
int main(void)
{
unsigned int n = 0;
scanf( "%u", &n );
while ( n-- )
{
unsigned int max_value = 0;
scanf( "%u", &max_value );
unsigned long long int sum = 0;
for ( unsigned int i = 1; i <= max_value; i++ )
{
size_t count = 0;
for ( unsigned int j = 1; j <= i; j++ )
{
if ( i % j == 0 ) ++count;
}
if ( count == 2 )
{
printf( "%u ", i );
sum += i;
}
}
printf( ": %llu\n", sum );
}
return 0;
}如果要进入
3
10
20
100则输出将为
2 3 5 7 : 17
2 3 5 7 11 13 17 19 : 77
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 : 1060https://stackoverflow.com/questions/66051375
复制相似问题