Reading fractions in C

徘徊边缘 提交于 2019-12-01 11:00:37

This uses sscanf to get the numbers, you can use scanf directly of course:

#include <stdio.h>
int main() {
  const char *s = " 13/6  \n";
  int a,b;
  sscanf(s, "%d/%d", &a, &b);
  printf("%d frac %d\n", a, b);
  return 0;
}

Keep a pointer to the head of the string.

Then look into using strchr() to get a second pointer that points to the / character.

You can then:

  1. Read characters from a dereferenced first pointer up until your first pointer is equal to the second pointer. Store those characters into a char [] or char * — that's your numerator as a C string.
  2. Read from the next character after where the second pointer points, up to the /0 nul terminator at the end of the string. Store those characters in a second char [] or char * — that's your denominator as a C string.

Use atoi() to convert both C strings to integers.

If strchr() returns NULL, then you can do error checking very easily because there was no / in the input string.

Alright. I've got a different way. Use strtol which will return to you a pointer to the '/' to which you add 1 and call strtol again for the second half.

This is twice as fiddly as the first answer, halfway as fiddly as the second. :)

#include <stdio.h>
#include <string.h>

int main(){
    char *f = " 12/7 ";
    char *s;
    long n,d;
    n = strtol(f, &s, 10);
    d = strtol(s+1, NULL, 10);
    printf(" %ld/%ld \n", n, d);
    return 0;
}

To answer the rest of your question, you definitely need 2 variables if it's going to be a fraction. If you can use floating-point internally and the fractions are just a nice feature for user input, then you can go ahead and divide them and store the number in one variable.

double v;
v = (double)n / d;

The cast to double is there to force a floating-point divide upon the two integers.

If, on the other hand you're going to have a lot of fractions to work with, you may want to make a structure to hold them (an object, if you will).

struct frac {
    long num;
    long den;
};
struct frac f = { 12, 7 };
printf("%ld/%ld\n", f.num, f.den);

you can make it this way also......

  char str[30];
  scanf("%s",str);
  char c[30];
  int i, num, denom;

  i = 0;
  while (*(str+i) != '/')
  {
      memcpy((c+i), (str+i), 1);
      i++;
  }
  *(c+i) = 0;
  i++;
  num = atoi(c);
  strcpy(c, (str+i));
  denom = atoi(c);
  printf("%d\n", num);
  printf("%d\n", denom);
#include <stdio.h>

typedef struct
{
int num, denom;
}fraction;

int main()
{
fraction fract = {1,2};

printf("fraction: %i/%i", fract.num, fract.denom);
return 0;
}

Here's what I generally do.

int main()
{
double a,b=1.0f,s;
scanf("%lf/%lf",a,b);
s=a/b;
printf("%lf",s);
}

Even if the user the doesn't enter the value of variable b the value is already initialized to 1.0f so it can calculate it's value anyway.

This is tried on Ubuntu with GCC.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!