读取数字序列并显示消息的C程序

时间:2018-10-14 05:08:25

标签: c

该程序应具有以下准则:

  1. 从标准输入中读取数字。
  2. 第一个数字是序列(n)的长度,后跟n个数字。(即,如果您输入“ 54321”,则序列的长度是5个数字)
  3. 如果n为0或负数,程序将显示消息“ Error_1” 通过在标准输入上换行。
  4. 如果长度短于n,则显示“ Error_2”,后跟新行并退出。

我发现第2点很困难

我的代码是:

#include <stdio.h>

int main() {

    int i,j,k;

    printf("Enter a Number:\n");
    scanf("%d", &i);

    if (i <= 0 ) {
        printf("Error_1\n");
    } else if(){
        printF("Error_2\n")
    }
}

4 个答案:

答案 0 :(得分:2)

|ID |NAME        |STREET         |CITY   |STATE|

|328|ADMIN HEARNG|939 W El Camino|Chicago|IL   |

所以我所做的是,我发现输入的数字的长度,如果长度与提供的长度不匹配,则会显示error2。我通过将数字连续除以10直到变为0来找出长度。

答案 1 :(得分:1)

您需要了解一些东西

您的代码:

"if (i <= 0 ) {

    printf("Error_1\n");

} else if () {/* I'm talking about this*/

    printF("Error_2\n")

}"

推荐:/ *它的意思是if(它为空!),您应该在if中写条件,您需要做的事情是if和if else not else if https://www.programiz.com/c-programming/c-if-else-statement * / 下面的当前代码:

#include <stdio.h>
int main()

{

    int num,cnt=0;

    printf("Enter length: "\n);
    scanf("%d", &num);

    while(num > 10) //checking first number
    {
      cnt++;
      num /= 10;
    }

    if(num <= 0)
    {
          printf("Error_01\n");
    }
    if(num == (count + 1)!)
    {
           printf("Error_02");
    }

    return 0;
}

答案 2 :(得分:1)

检查一下。您可以使用以10为底的对数来计算序列的长度。更轻松,更清晰。 要使用-lm标志编译代码,请参见以下命令: gcc sampleFilename.c -lm

#include <stdio.h>
#include<math.h>

int main() {

    int i,num, length;

    printf("Enter a Number:\n");
    scanf("%d", &i);

    if (i <= 0 ) {
        printf("Error_1\n");
    } 
    else{
         printf("Enter the number: ");
         scanf("%d",&num);
         length=(int) log10(num)+1;// compute the length of the number .. read about log10
         if (length < i ) //length of the sequence is less than the number 'i'
             printf("Error_2\n");
    }
}

答案 3 :(得分:0)

尝试以下代码,

希望这会起作用

#include <stdio.h>

int main()
{
    int i,j,k;


    printf("Enter any number: \n");
    scanf("%d", &i);

    k = 0;

    if(i <= 0)
    {
          printf("Error_01\n");
    }

    printf("Enter value number: \n");
    scanf("%d", &j);


    while(j != 0) // check till first digit
    {

        k++;

        j /= 10;
    }


    if(k != i)
    {
           printf("Error_02\n");

    }

    return 0;
}

通过引用此方式 https://codeforwin.org/2016/10/c-program-to-count-number-of-digits-in-number.html