#include <stdio.h>
void main()
{
int n,i;
int arr[5]={5,4,3,2,1};
int *ptr;
printf("input the number you want to find:\n");
scanf("%d",&n);
for(i=0;i<5;i )
if(arr[i]==n)
{
ptr=&arr[i];
printf("number '%d' is present in the array and it is the %d st/nd/rd/th term in the array.\n its address is: %d",n,i 1,ptr);
}
}
**> 我添加了 else printf("number not found"); 在這里,但它也回圈和列印了很多 **
uj5u.com熱心網友回復:
保持簡單......只需在回圈后添加列印并在匹配時添加回傳。
喜歡:
#include <stdio.h>
int main(void)
{
int n,i;
int arr[5]={5,4,3,2,1};
int *ptr;
printf("input the number you want to find:\n");
if (scanf("%d",&n) != 1)
{
// Input error
exit(1);
}
for(i=0;i<5;i )
{
if(arr[i]==n)
{
ptr=&arr[i];
printf("number '%d' is present in the array and it is the %d st/nd/rd/th term in the array.\n its address is: %p",n,i 1,(void*)ptr);
return 0; // Done... just end the program
}
}
puts("not found");
}
順便提一句:
注意它應該是 int main(void)
注意,指標是使用被列印%p有澆注到(void*)
uj5u.com熱心網友回復:
- 始終檢查
scanf!!的回傳值 - 初始化指向 NULL 的指標。如果什么也沒找到,它將保持為 NULL
- 使用正確的地址格式 (
%p),并(void *)在傳遞給之前將指標轉換為printf main回傳型別是int.
int main()
{
int n;
int arr[]={5,4,3,5,2,5,1};
int *ptr = NULL;
printf("input the number you want to find:\n");
if(scanf("%d",&n) == 1)
{
for(size_t i=0;i<sizeof(arr)/ sizeof(arr[0]);i )
if(arr[i]==n)
{
ptr=&arr[i];
printf("number '%d' is present in the array and it is the %zu st/nd/rd/th term in the array.\n its address is: %p",n,i 1, (void *)ptr);
}
if(!ptr) printf("NUMBER NOT FOUND!!!!!\n");
}
else
{
printf("SCANF ERROR\n");
}
}
https://godbolt.org/z/6zcE4nnz8
uj5u.com熱心網友回復:
只需將 printf 的呼叫放在 for 回圈之外。例如
int *ptr = NULL;
printf("input the number you want to find:\n");
scanf("%d",&n);
for( i = 0; ptr == NULL && i < 5; i )
{
if ( arr[i] == n )
{
ptr = arr i;
}
}
if ( ptr != NULL )
{
printf("number '%d' is present in the array and it is the %td st/nd/rd/th term in the array.\n its address is: %p\n",
n, ptr - arr 1, ( void * )ptr );
}
else
{
printf( "number %d is not present in the array.\n", n );
}
也不要使用像5. 而是使用命名常量。并在使用它們的最小范圍內宣告變數。并且使用%d帶有指標的轉換說明符具有未定義的行為。您需要使用轉換說明符%p。
這是一個演示程式。
#include <stdio.h>
int main(void)
{
int arr[] = { 5, 4, 3, 2, 1 };
const size_t N = sizeof( arr ) / sizeof( *arr );
int n = 0;
printf( "input the number you want to find (default is %d): ", n );
scanf( "%d", &n );
int *ptr = NULL;
for ( size_t i = 0; ptr == NULL && i < N; i )
{
if ( arr[i] == n )
{
ptr = arr i;
}
}
if ( ptr != NULL )
{
printf( "number '%d' is present in the array and it is the %td st/nd/rd/th term in the array.\n its address is: %p\n",
n, ptr - arr 1, ( void * )ptr);
}
else
{
printf( "number %d is not present in the array.\n", n );
}
}
程式輸出可能看起來像
input the number you want to find (default is 0): 3
number '3' is present in the array and it is the 3 st/nd/rd/th term in the array.
its address is: 0x7ffefecb1778
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/316399.html
上一篇:DVWA靶場命令執行(小白筆記)
