朋友我是c的新手,所以我在a,code中遇到问题,如果我的逻辑中有任何错误,请将其视为赦免,
我试图在二维数组中找到元素,所以我在我的代码中声明了一个二维数组,我将采用用户输入,输入将与完整数组中的数据进行比较,列索引为2维数组,如果发现任何类似于该列索引的数据,那么它将给出另一列数组的相同行数据。如果我在我的代码中给出一个输入,它给出的数字的输出不在数组索引中,虽然数字在数组索引中,所以我不明白我的错在哪里。
PLZ帮我解决问题。
这是我的代码:
#include<stdio.h>
int main()
{
int arr[10][3]={{1,5},
{2,8},
{3,27},
{ 4,64},
{5,125},
{6,216},
{ 7,343},
{8,512},
{ 9,729},
{ 10,1000}};
int i, num;
printf("Enter a number\n");
scanf("%d",&num);
for(i=0;i<10;i++)
{
if (num==arr[i][0])
printf("%d",arr[i][1]);
break;
}
if (num==10)
printf("the number is not there");
return 0;
}
答案 0 :(得分:3)
你有一个错误的分号:
if (num==10);
printf("the number is not there");
对printf
的调用每次都会运行,因为if
语句没有正文。格式更好:
if (num==10);
printf("the number is not there");
正如@zoska指出的那样,你也有同样的错误:
if (num==arr[i][0]);
答案 1 :(得分:0)
我会至少做以下三次更改:
将int arr[10][3]
更改为int arr[10][2]
更改
if (num==arr[i][0]);
printf("%d",arr[i][1]);
到
if (num == arr[i][0]) {
printf("%d",arr[i][1]);
}
更改
if (num==10);
printf("the number is not there");
到
if (i == 10) { // note: 'num' changed to 'i'
printf("the number is not there");
}
答案 2 :(得分:0)
您的代码将来会如此
#include <stdio.h>
int main(void)
{
int arr[10][2] = {
{1,5},
{2,8},
{3,27},
{4,64},
{5,125},
{6,216},
{7,343},
{8,512},
{9,729},
{10,1000}
};
int i, num;
printf("Enter a number\n");
scanf("%d", &num);
for(i = 0; i < 10; i++)
{
if (num==arr[i][0]) {
printf("%d", arr[i][1]);
break;
}
}
if (i == 10) {
printf("the number is not there");
}
return 0;
}