This is the code prompting the user for input
#include <stdio.h>
#include <cs50.h>
//prompt user for number
int main(void)
{
long number = get_long("Enter card number: ");
}
This is the code prompting the user for input
#include <stdio.h>
#include <cs50.h>
//prompt user for number
int main(void)
{
long number = get_long("Enter card number: ");
}
The below program will help you, but its bettor to give some effort
#include <stdio.h>
#include <cs50.h>
//prompt user for numb er
int main(void)
{
long number = get_long("Enter card number: ");
int count = 0;
do{
number = number / 10;
++count;
}while (number != 0) ;
printf("length of number = %d",count);
}
You can do for instance:
#include <stdio.h>
#include <string.h>
void main()
{
long alpha = 352;
char s[256];
sprintf(s,"%ld",(alpha >= 0L) ? alpha : -alpha );
printf("long digits: %lu",strlen(s));
}
If you allow yourself to use floating point, the number of digits of a positive integer number A
in base B
is the logarithm of A in base B plus 1. Working in base 10 you could write:
long get_num_digits(long a)
{
long c;
if (a == 0) {
return 1;
}
if (a < 0) {
a = -a;
}
c = (long)log10((double)a);
++c;
return c;
}
This version addresses an issue raised by Andrew Henle and is capable of dealing with a long with an arbitrary number of bits.
After the necessary precautions treating non-positive arguments, we calculate the log of the argument in base 2 and change the log base to base 10 by multiplying by lod_10(2).
The number of digits from the base 10 log of 2 must be chosen accordingly. The following version is good from 1 to 1000 bits longs, uses no floating point, one integer multiplication, one interger division and a maximum of N-1 shifts, where N is the number of bits of the argument.
/*
* Using 3 digits from log_10(2), we have enough precision to calculate the
* number of digits of a 1000 bit number.
*/
/* #define LOG_10_2 301029995663981198 */
#define LOG_10_2_NUMERATOR 301
#define LOG_10_2_DENOMINATOR 1000
long get_num_digits3(long a)
{
long c;
long i;
if (a == 0) {
return 1;
}
if (a < 0) {
a = -a;
}
/* i = log_2(a); */
i = 0;
while (a) {
a >>= 1;
++i;
}
/* c = log_10(a) + 1 */
c = (long)(LOG_10_2_NUMERATOR * i);
c /= LOG_10_2_DENOMINATOR;
++c;
return c;
}