编写c程序,用户获取一个包含n个元素的数组,并找到值为数字5的倍数的元素。这些元素及其值显示在屏幕上,如下所示:V[i]=a,V[j]=b,。。。。我的代码:
#include <stdio.h>
int main ()
{
int n,i,sh=0;
int v[100];
printf ("Please write n:");
scanf("%d",&n);
for (i=0;i<n;i++)
{ printf ("n Write the element %d",i);
scanf("%d",&v[i]);
}
if (v[i] %5)
printf("The element is a multiple of 5",&sh);
return 0;
}
它编译得很好,但当我运行它并编写元素时,它什么也不做。。我哪里错了?
编辑:
Yes,here it is :
Please write n: 4
Enter value 0: 10
Enter value 1 : 9
Enter value 2 : 20
Enter value 3:14
V[0]=10,V[2}=20
您的代码中有三个错误。
-
第一个
if ( v[i] % 5 )
在结束时处于循环之外,它只会为i = n+1
尝试一次。你会遇到越界的问题。 -
并且搜索
5
的倍数,所以条件应该是if ( v[i] % 5 == 0 )
。 -
之后,您的
printf
也是错误的。printf("The element is a multiple of 5",&sh); // ^^^^
什么是sh
?为什么要在printf
中使用它?格式化字符串似乎不需要参数。
你的代码应该是这样的:
for ( i=0; i < n; i++ )
{
printf( "n Write the element %d", i );
scanf( "%d", &v[i] );
if ( v[i] % 5 == 0 )
printf( "The element is a multiple of 5" );
}
编辑:
对于输出的例子,也许你应该做另一个循环:
#include <stdio.h>
int main ()
{
int n, i, sh = 0; // I still don't for what sh is used ...
int v[100];
printf ("Please write n:");
scanf("%d",&n);
// Get the values
for ( i=0; i < n; i++ )
{
printf( "n Write the element %d", i );
scanf( "%d", &v[i] );
}
// Print the values multiple of 5
for ( i=0; i < n; i++ )
{
if ( v[i] % 5 == 0 )
printf( "V[%d]=%dn", i, v[i] );
}
return 0;
}
这是一个工作的例子。
- IF语句不在循环中
printf("The element is a multiple of 5",&sh);
-我是不是错过了什么?(为什么&sh?)- IF的说法并不完全正确
如何编辑:
1| #include <stdio.h>
2|
3| int main ()
4| {
5| int n,i,sh=0;
6| int v[100];
7| printf ("Please write n:");
8| scanf("%d",&n);
9| for (i=0;i<n;i++)
10| {
11| printf ("n Write the element %d",i);
12| scanf("%d",&v[i]);
13|
14| if ((v[i] % 5) == 0)
15| printf("The %d. element %d is a multiple of 5", i+1, v[i]);
16| }
17|
18| return 0;
19| }
只是想知道变量sh的目的是什么?或者作者想用它做什么?
这:
if (v[i] %5)
printf("The element is a multiple of 5",&sh);
在第一个循环之后,您的i
等于n+1
。你不会重置它,也不会在循环中检查你的元素
此外,您的格式字符串中没有任何%p
,为什么要传递%sh
?
做一些类似的事情:
for (i=0;i<n;i++)
if (v[i] %5) // not divided by 5
// Correct prtinf() statement
// printf("The element v[%d] = %d is NOT multiple of 5", i, v[i]);
{
int n,i,sh=0;
int v[100];
printf ("Please write n:");
scanf("%d",&n);
for (i=0;i<n;i++)
{ printf ("n Write the element %d",i);
scanf("%d",&v[i]);
}
/// now go back through the array
//
for( i = 0; i < n; i++ )
if( v[i] % 5 == 0 )
printf( "The element at %d is %d, divisible by 5n", i, v[i] );
return 0;
}
int n,i,sh=0;
//array to hold the numbers
int N[100];
//count of numbers
printf ("Enter the NUMBER count :");
scanf("%d",&n);
//获取数组中的输入对于(i=0;i
//check for the divisibility
for( i = 0; i < n; i++ )
if( N[i] % 5 == 0 )
printf( "The element at %d is %d, divisible by 5n", i, N[i] );
return 0;
}