如何用C语言为每个数组元素分配一个4位数字 [英] How to assign a 4 digit number to each element of array in C language

查看:472
本文介绍了如何用C语言为每个数组元素分配一个4位数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为数组分配一个4位数字,不应该只有4位数,然后它不会忽略数字并再次接受输入



代码块添加 - OriginalGriff [/ edit]



我尝试过:



i want to assign a 4 digit number to array no should be of 4 digit only and it is not then ignore number and again take the input

[edit]Code block added - OriginalGriff[/edit]

What I have tried:

#include <stdio.h>
    #include <stdlib.h>
    
    int main()
    {
        int a[5]; //array
        int i=0;
        int temp,rem=0;
        for(i=0;i<5;i++)
        {
            scanf("%d",&a[i]); //taking input from user
            while(a[i]/10!=0)
            {
                    rem=a%10;  //condition check but this part is not working
                    temp++;   //increasing temp one by one
                    a[i]=a[i]/10; //dividing the no by 10
            }
    
                if(temp==4)
                {
                        printf("no is acceptable "); //if digit is of 4 then no //is acceptable
                        temp=0;
                }
                else
                {
                    printf("please again enter the 4 digit no");
                    scanf("%d",&a[i]); //again scan the no and again check the //condition
                    while(a[i]/10!=0)
                    {
                            rem=a%10;
                            temp++;
                            a[i]=a[i]/10;
                    }
    
                        if(temp==4)
                        {
                                printf("no is acceptable "); //if count is 4 //then only no is acceptable
                                temp=0;
                        }
                }
        }
        for(i=0;i<5;i++)
        {
            printf("%d",a[i]); //printing the no
        }
        return 0;
    }

推荐答案

为什么要检查数字是否有四位带循环模数的数字?

Why are you checking the number has four digits with modulus in a loop?
if (a[i] >= 1000 && a[i] <= 9999)
   {
   // It has four digits
   ...
   }


您的代码看起来很复杂!

任何4位数的整数都在1000到9999之间。

Your code look complicated !
Any integer with 4 digits is between 1000 and 9999.
if (a[i]>=1000 && a[i]<=9999) {
    ...
}


这篇关于如何用C语言为每个数组元素分配一个4位数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆