gpt4 book ai didi

C语言 : I want to see if a value of a[] is less than all the values of b[]

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:21:20 25 4
gpt4 key购买 nike

我必须用 C 解决一个练习。这个练习要求我从输入中获取 2 个数组 (a, b) 并查看是否有 a[] 的值小于 b 的所有值。两个数组都有 3 个元素。我写的代码如下:

for (int i = 0; i < 3; ++i)
{
while(k<3)
{
if(a[i]<a[k])
{
count++;
if (count==3)
{
break;
}
}
k++;
}
count=0;
}

if (count==3)
{
printf("TRUE");
}
else
{
printf("FALSE");
}

代码的问题在于它在我提供的任何输入中都打印错误。任何帮助,将不胜感激。附言我省略了数组的键盘扫描和 i 和 k 的声明,以使代码简短明了。

最佳答案

对于初学者来说,不要使用像 3 这样的魔数(Magic Number)。而是使用命名常量。

在这个声明中

if(a[i]<a[k])

您正在比较同一数组 a 的元素,而不是将 a 的元素与数组 b 的元素进行比较。

同样在 while 循环之前,您必须将变量 countk 设置为 0。

for (int i = 0; i < 3; ++i)
{
k = 0;
count = 0;
while(k<3)

break 语句会中断 while 循环,但不会中断外部 for 循环。

代码没有确定小于数组b所有元素的数组a的目标元素的位置。

您可以编写一个单独的函数来完成该任务。

这是一个演示程序。

#include <stdio.h>

size_t find_less_than( const int a[], const int b[], size_t n )
{
size_t i = 0;

for ( _Bool found = 0; !found && i < n; i += !found )
{
size_t j = 0;
while ( j < n && a[i] < b[j] ) j++;

found = j == n;
}

return i;
}

int main(void)
{
enum { N = 3 };

int a[N], b[N];

printf( "Enter %d values of the array a: ", N );
for ( size_t i = 0; i < N; i++ ) scanf( "%d", &a[i] );

printf( "Enter %d values of the array b: ", N );
for ( size_t i = 0; i < N; i++ ) scanf( "%d", &b[i] );

size_t i = find_less_than( a, b, N );
if ( i != N )
{
printf( "The element at position %zu with the value %d of the array a\n"
"is less than all elements of the array b\n", i, a[i] );
}
else
{
puts( "There is no element in the array a\n"
"that is less than all elements of the array b\n" );
}

return 0;
}

它的输出可能看起来像

Enter 3 values of the array a: 3 0 1
Enter 3 values of the array b: 1 2 3
The element at position 1 with the value 0 of the array a
is less than all elements of the array b

关于C语言 : I want to see if a value of a[] is less than all the values of b[],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49334717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com