繁体   English   中英

“ For循环”以升序排列数字。 [ERROR]指针和整数比较

[英]'For loop' to arrange Numbers in ascending order. [ERROR] pointer and integer comparision

这是一个非常简单的程序,可以按升序排列数字。 现在,我不知道在所有的for循环中它如何表示整数和指针之间存在比较。 顺便说一句,我是菜鸟。

#include <stdio.h>

int main()
{

    int number[100],total,i,j,temp;;

    printf("Enter the quantity of the numbers you want \n");
    scanf("%d",&total);

    printf("Enter the numbers \n");
    for(i=0; i<total; i++){

        scanf("%d",&number[i]);
    }

    for(i=0; i < (number-1); i++){ 

        for(j=(i+1); j  < number; j++){  

            if(number[i]>number[j]){
                temp = number[i];
                number[i] = number[j];
                number[j] = temp;
           }

        }

    }
    for(i=0; i < number; i++){  

        printf("%d \n", number[i]);
    }



    return 0;
}

您正在使用i < number ,其中iint并且number是一个array

只需将这些行更改为下面

for(i=0; i < (total-1); i++){ 

        for(j=(i+1); j  < total; j++){  


for(i=0; i < total; i++){ 

以下建议的代码:

  1. 正确检查错误
  2. 正确将错误消息输出到stderr
  3. 适当地最小化变量的范围
  4. 干净地编译
  5. 在逗号后,分号后,括号内,C运算符周围包含适当的水平间距
  6. 执行所需的功能
  7. 利用VLA(可变长度数组),因此数字的数量最多可以是任何正数
  8. 通过单个空白行分隔代码块(例如,如果是,则是…,则是…,是……时,切换,区分大小写)
  9. 不包含随机空白行
  10. 说明为什么包含每个头文件
  11. 不允许用户为数字输入负数
  12. 遵循公理: 每行仅一个语句,每个语句(最多)一个变量声明。

现在,建议的代码:

#include <stdio.h>   // scanf(), perror(), printf()
#include <stdlib.h>  // exit(), EXIT_FAILURE

int main( void )
{
    int total;

    printf("Enter the quantity of the numbers you want \n");
    if( 1 != scanf( "%d", &total ) )
    {
        perror( "scanf for count of numbers failed" );
        exit( EXIT_FAILURE );
    }

    // implied else, scanf successful

    if( !total )
    {  // then 0 entered
        printf( "Exiting, no numbers to enter\n" );
        return 0;
    }

    // implied else, some numbers to enter

    int number[ total ];   // << uses the VLA feature of C

    for( unsigned i = 0; i < total; i++ )
    {
        printf( "Enter number %u: ", i+1 );

        if( 1 != scanf( "%d", &number[i] ) )
        {
            perror( "scanf for a number failed" );
            exit( EXIT_FAILURE );
        }

        // implied else, scanf successful
    }

    for( int i = 0; i < (total - 1); i++ )
    {
        for( int j = (i+1); j < total; j++ )
        {
            if( number[i] > number[j] )
            {
                int temp  = number[i];
                number[i] = number[j];
                number[j] = temp;
            }
        }
    }

    for( unsigned i = 0; i < total; i++ )
    {
        printf("%d \n", number[i]);
    }

    return 0;
} // end function: main

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM