"Chenjun Hou" <23*6*8*
9@s*u*e*t*u*a*e*u*a*> wrote:
> How exactly can we ensure that integers are printed in that way without using 2 separate data types? Isn't it possible for an integer stored as float to have imprecision?
There are no
integers in the ml program, all the constants are real numbers, as that is the only datatype supported by ml. So, all the constant
integer values in the ml program are actually floats. e.g. "2" is technically "2.0". If there are rounding errors in your program there will be in the program used to mark it, since it would also be using floating point values for everything.
>
> ```
> if (nearbyint(count + count * count - count * count * x) == count + count * count - count * count * x) {
> print("%.0lf\n", count + count * count - count * count * x);
> } else {
> print("%.6lf\n", count + count * count - count * count * x);
> }
> ```
> to check whether the result of the expression is an integer
This is one way you could do it. Or you could evaluate the result of the expression and place it in the c code since you will likely need to check the identifiers in the string anyway.
> We would need to store the entire expression of count + count * count - count * count
as a string and substitute it into the code generated, which can only be done with dynamic memory allocation, since the expression isn't guaranteed to have a maximum length.
Technically you don't need dynamic memory allocation, you could have a large array, copy the string into the array, and as long as the string is terminated by a '\0' then any string operations will stop at that point.
Here is some code for you to play with:
#include <stdio.h>
#include <string.h>
int main() {
char buffer[1000]; //note the excessively large buffer
char line[10000]; // note the even larger buffer
float pi = 3.14159;
sprintf(buffer, "The value of pi is %.2f.", pi);
sprintf(line, "%s %s", buffer, buffer);
printf("%s\nlength of line is %i\n", line, strlen(line));
//floats
float num = 20.5;
float num2 = 1.12321;
float num3 = 3;
if(num == (int) num)
{
printf("int\n");
} else {
printf("float\n");
}
printf("%.7f\n", num2 + num3);
printf("%.7f\n", num * num2);
printf("%.7f\n", num + num2);
printf("%.7f\n", num3 * num3);
return 0;
}