c - 我如何在不使用数组的情况下解决问题,因为数组现在对我来说很复杂?
问题描述
问题是:- 编写一个 C 代码,要求用户输入 10 个数字,然后要求他输入另一个数字以在 10 个数字中搜索并打印其位置以防万一。如果没有找到号码,它将打印号码不存在。
我写的代码是:-
#include<stdio.h>
void main(void)
{
int n, i, value,j;
for (i=1;i<=10;++i)
{
printf("enter number %d : ",i);
scanf("%d",&n);
}
printf("Enter the value to search: ");
scanf("%d",&value);
/*next part of code is not correct
that can not search to find the place of number */
for (j=1;j<=10;++j)
{
if (value == n)
{
printf("value is exist at element number %d",n);
}
else
{
printf("value is not exist\n");
}
}
}
输出将是:-(输入数字后)。
Enter the value to search is 12.
value is exist at element 9
解决方案
#include <stdio.h>
int main(){
//there are 10 int in n
int n[10], i, value;
for (i=0;i<10;i=i+1)//array count from 0 ,i=i+1 same as i++
{
printf("enter number %d : ",i);
scanf(" %d",&(n[i]));//& mean get address so you will push what you input to n[0]~n[9]
//little tip before %d remain a space for some reason if you keep learn you will know
}
printf("Enter the value to search: ");
scanf(" %d",&value);//& mean get address so you push what you input to value here
for (i=0;i<10;i=i+1)
{
if (value == n[i])
{
printf("value is exist is element number %d\n",n[i]);
break;//break mean out of for loop
//
}
}
if(i==10){//if search all not found then i will be 10 because after loop i will +1
//if break i will not +1
printf("value is not exist\n");
}
return 0;//remember "int" main() so you need return 0
}
不断学习你会更强大 数组很简单
推荐阅读
- mysql - 使用 flask-migrate 时出现 Flask 迁移错误
- c++ - 有没有办法在没有命名空间的 c++ 中嵌套枚举?
- android - 使用 androidx.transition.Slide 的片段转换似乎重新排序视图 z 索引
- java - 同一行代码中的两条指令
- function - FHIR 一个演员扮演两个不同的角色
- javascript - 重新加载页面后显示警报
- java - 如何将对象存储在内存中并在 Max(amount, time) 之后将它们刷新到目的地
- c# - 在 Godaddy 上部署 Asp Net Core 2.2 网站后出现错误 403
- javascript - 即使结果正确,函数也不会在 ref.on() 中响应
- highcharts - 在没有日期的 Highcharts 中使用 RangeSelector