-
Holy moly!!!
Hey folks,
I am completely new to C programming(just started taking it in a class at school).. I have a question.
I am making an if/else statement.
Code:
if (column_number<5&&column_number>0)
{
printf("The average of column %i is: %.3le", column_number,average);
}
else
{
printf("Invalid column number");
}
So basically, if the number isnt 1 through 4, then it prints the "invalid column". But if I type in 2.4 or 3.5 it doesnt go to the invalid column statement. What signs can I use to make only 1,2,3 and 4 work ????
Thanks.. I have a feeling ill be on this forum a lot...
P.S.. i know my format (neatness) needs work
-
Cast the float/double to an int?
-
If you declared column_number as a int and then you are reading the user input with something like scanf("%d", &column_number); what will happen basically if the user enter something like 2.4, is that scanf will read and store the value 2 in column_number. This is how works scanf for integer, it reads the keyboard buffer for numeric character until it read a non-numeric character (approximately).
There would be different way to do so if the user enter something like 2.4. Like reading the user input in a buffer with fgets, than reading the buffer for an int with sscanf and reading again the buffer with sscanf for a float, then casting the int value to the float and checking if the comparaison is true; in that case, you could assume that the user enter a "real" integer.
I think that would work (but i have not tested).
(Edit: i just tested it and it does work. Here's my test program heh)
Code:
#include <stdio.h>
#define TAILLE 50
int main()
{
char chaine[TAILLE];
int i;
int entier;
float flottant;
printf("Enter a number: ");
fgets(chaine, TAILLE, stdin);
i = sscanf(chaine, "%d", &entier);
if (i != 0)
{
sscanf(chaine, "%f", &flottant);
if ((float) entier == flottant)
{
printf("Integer number.\n");
}
else
{
printf("Decimal number.\n");
}
}
else
{
printf("That's not even a number, moron.\n");
}
getchar();
return 0;
}
-
cant find "fgets" in my textbook... what is that?? I will show you all the code that I have written...
Code:
#include "utils.h"
#include <stdio.h>
#define filename "data.txt"
int main ()
{
int column_number;
double average;
FILE *f;
f=fopen("data.txt", "r");
printf("Enter the column number: ");
scanf("%i", &column_number);
average = column_average(f,column_number);
if (column_number<5&&column_number>0)
{
printf("The average of column %i is: %.3le", column_number,average);
}
else
{
printf("Invalid column number");
}
return 0;
}
-
-
ahhh.. got it.. thanks folks... I'll be back.. haha. guarenteed