I want to check if the user input is purely integer or a float. I attempted to do this by using floor and ceilfand comparing the values to the original x value in a function. However, this seems to be a tad bit problematic as the function keeps returning 0 instead of 1 for certain numbers like 5.5, when floor(5.5)!=5.5 and ceilf(5.5)!=5.5. This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>
#include <stdbool.h>
int intchecker(float x)//in a separate file
{
if (floor(x)==x && ceilf(x)==x)
{
//printf("%f",floor(x));
return 0;
}
else {
return 1;
}
}
int main()
{
char line[] = " +----+----+----+----+----+----+----+----+----+----+---+";
char numbers[] = " 0 5 10 15 20 25 30 35 40 45 50";
float balls,slots;
int slot[9];
printf("==========================================================\nGalton Box Simulation Machine\n==========================================================\n");
printf("Enter the number of balls [5-100]: ");
scanf("%f",& balls);
if (balls>100 || balls<5){
printf("/nInput is not within the range. Please try again.");
}
else if (intchecker(balls)==1){
printf("/nInput is not an integer. Please try again.");
}
else {
printf(" This is an integer.");
//some more code here
}
}
I tried placing just the intchecker code in another project, which seems to work fine without any bugs, unlike in the previous project, where when I used a printf statement to check if the floor(x) value was correct, it kept showing different answers, e.g. "-2.000000" when input was 5.2. This is my code for the second project:
#include <stdio.h>
#include <stdlib.h>
#include<math.h>
int main()
{
float x;
scanf("%f",&x);
if (floor(x)==x && ceilf(x)==x){
printf("Integer");
return 0;
}
else {
printf("Non-Integer");
return 1;
}
}
How is it possible that the second code works perfectly when the first code does not? Is something wrong with my way of writing/calling the function?(I am relatively new to functions-only 2 weeks of exposure so far)
I searched online and have seen many answers to check if input is integer or float, even on stackoverflow.com itself, but my wish is not to find out other ways to check if input is integer or float (for if I wished to do that, I could just google it, and there are many such questions on stackoverflow.com as well), but to comprehend why my first code does not work, for, as far as I know, it ought to work well without any of the bugs it is currently facing.
Any help is greatly appreciated!:)
Assuming a missing function declaration:
main.c is missing the prototype for int intchecker(float x) so main.c assumes the old-school prototype of int intchecker(int x) and the code exhibits undefined behavior. Anything could happen.
Add prototype in main.c or put it in separate.h and include that header file here and in separate.c
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <conio.h>
#include <stdbool.h>
int intchecker(float x);
int main(void) {
...
Related
I'm implementing a basic program which generate 2 random number. The problem is the result of first number looks like it is following some kind of pattern, but the second still looks right.
Output:
6584 679
6587 1427
6591 9410
6594 156
7733 3032
7737 3780
This is my code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
srand(time(NULL));
int a = rand()%10001, b= rand()%10001;
printf("%d %d", a,b);
return 0;
}
So what is the problem here and how to fix it.
Any help would be appreciated.
I am using windows 10 64 bits, gcc 8.1.0.
time(NULL) value acts as the same seed value every time you run the program. The reason behind that your CPU will generate a similar starting NULL time for every time. To get rid of this kind of effect you need to play with the seed value, so that even if your computer starts with the same time(NULL) value, it needs to get seed different than the other runs. For that purpose, you can simply do the following:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int main(){
srand((unsigned)time(NULL) * (unsigned)getpid());
int a = rand()%10001, b= rand()%10001;
printf("%d %d", a,b);
return 0;
}
Full credit to #pmg, thanks for the comments to improve the solution.
I'm a novice C programmer and am completely stuck on debugging a program that relies on the CFITSIO package [sorry in advance if I get the terminology wrong below]. I have two fits that I am reading in: 1. "BFmask.fits", 2. "DFmask.fits". These are two files that either have a 1 or a 0 as elements.
These are defined as double precision pointers as below:
double *maskdark,*maskbright;
Memory allocation is as follows:
maskdark=malloc(size*sizeof(double)); //dark mask
maskbright=malloc(size*sizeof(double)); //bright mask
where "size" is a long variable with a value of 490000
THE PROBLEM: When I execute the program, it apparently does not properly read in BFmask.fits or DFmask.fits (i.e. does not properly read in entries for maskbright or maskdark).
HOWEVER, when I declare a third variable called 'mask' (i.e. double *mask;), then the program DOES execute properly.
What is the cause and solution to this problem?
How do I avoid similar ones in the future?
I have checked dozens of times to make sure this variable is not used anywhere in the program. This makes no sense to me.
#include <stdio.h>
//For declaration of open, close
#include <sys/stat.h>
#include <fcntl.h>
#include <math.h>
#include <unistd.h>
#include <time.h>
//GSL Matrix STuff
#include <gsl/gsl_vector.h>
#include <gsl/gsl_math.h>
#include <gsl/gsl_matrix.h>
#include <gsl/gsl_eigen.h>
#include <gsl/gsl_blas.h>
//CFITSIO
#include <fitsio.h>
int main ()
{
long sizetotdm,cmwfsbrightindex,cmwfsdarkindex;
long size,sizex,sizey;
double *maskdark,*maskbright;
//double *mask; //if I uncomment this, then the program works properly somehow
fitsfile *fptr;
float nullval;
int status, anynull;
cmwfsbrightindex=0;
cmwfsdarkindex=0;
sizex=700; sizey=700; size=sizex*sizey;
/* Define Masks for Dark Field and Bright Field */
maskdark=malloc(size*sizeof(double)); //dark mask
maskbright=malloc(size*sizeof(double)); //bright mask
/* Read in Dark and Bright Field Mask files */
sprintf(s_file,"./06_21_19_mask/BFmask.fits");
fits_open_file(&fptr,s_file,READONLY,&status);
fits_read_img(fptr,TDOUBLE,1,size,&nullval,maskbright,&anynull,&status);
sprintf(s_file,"./06_21_19_mask/DFmask.fits");
fits_open_file(&fptr,s_file,READONLY,&status);
fits_read_img(fptr,TDOUBLE,1,size,&nullval,maskdark,&anynull,&status);
for (i=0;i<size; i++)
{
if (*(maskbright+i)==1)
{
cmwfsbrightindex+=1;
}
if (*(maskdark+i)==1)
{
cmwfsdarkindex+=1;
}
}
printf("the number of pixels is %ld %ld \n",cmwfsbrightindex,cmwfsdarkindex);
}
Results should be ...
the number of pixels is 24212 24952 //this happens when I define an unused variable
The results are ...
the number of pixels is 0 0 //this happens when I comment out the unused variable
I'm trying to create a program that needs to get string input from the user, since it's has to work with portuguese words i'm using wchar_t,the problem is,
C seems to have a will, because when i need it to work it doens't but then out of the blue it works in some simple test.
the following code worked 5 minutes ago and now it doesn't:
#include <stdio.h>
#include <wchar.h>
#include <locale.h>
/
int main(){
setlocale(LC_ALL,"Portuguese");
wchar_t meu[3];
fgetws(meu,3,stdin);
fputws(meu,stdout);
return 0;
}
I'm writing a program for vocabulary training, for myself. And the program itself should be available in different languages, atm in German and English.
What I want is to have a main file which manage all and two separate files for the functions in the right language.
I compile all the files with:
gcc vocTrainer.c german_menue.c english_menue.c -o v.exe
But I get an error of multiple definition even though I only include one of the language files depending on your input.
Multiple defintion of 'orderOfVoc'
First defined here: collect2.exe error: ld returned 1 exit status
My code:
vocTrainer.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "german_menue.h"
#include "english_menue.h"
int main(void)
{
char selectLang[1]; //store 1 for English or 2 for German
system("cls"); //clear screen
memset(selectLang,0,1); //set all fields in the array to 0
while(selectLang[1] != 1 && selectLang[1] != 2)
{
//select your language
printf("Choose language - Sprache auswaehlen:\n(1) - Englisch/English\n(2) - Deutsch/German\n");
scanf("%d",&selectLang[1]);
system("cls");
}
//language query
if(selectLang[1] == 2)
{
#include "german_menue.c"
}
else
{
#include "english_menue.c"
}
printf("Test of select Order: %d",orderOfVoc());
return 0;
}
german_menue.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "german_menue.h"
int orderOfVoc()
{
char selectOrder[1]; /*store the choosen order of vocabulary.
1 for one after another 2 for a random sequence of words*/
printf("Wie sollen die Vokabeln abgefragt werden?\n(1) - Der Reihe nach\n(2) - Zufaellig\n");
scanf("%d",&selectOrder[1]);
return selectOrder[1];
}
english_menue.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "german_menue.h"
int orderOfVoc()
{
char selectOrder[1]; /*store the choosen order of vocabulary.
1 for one after another 2 for a random sequence of words*/
printf("How do you want to learn the vocabulary?\n(1) - Vocabulary in order\n(2) - Random order\n");
scanf("%d",&selectOrder[1]);
return selectOrder[1];
}
german_menue.h
#ifndef GERMAN_MENUE_H //include guards
#define GERMAN_MENUE_H
extern int orderOfVoc();
#endif //GERMAN_MENUE_H
english_menue.h
#ifndef ENGLISH_MENUE_H //include guards
#define ENGLISH_MENUE_H
extern int orderOfVoc();
#endif //ENGLISH_MENUE_H
Primary Issue: In your code,
if(selectLang[1] == 2)
{
#include "german_menue.c"
}
else
{
#include "english_menue.c"
}
is not doing what you're thinking. There are may issues, like
#include is compile time operation (during preprocessing state) and essentially cannot be controlled at runtime.
You don't include source files. You compile and link them together. Your compilation statement looks correct. Just leave out the above mentioned code snippet from your code.
Just to add a bit detail regarding the reason behind the error you received, is because, you have #includeed the source files (which is essentially adding the source code of that .c file in vocTrainer.c file itself) and again, at compile time, you're putting the .c files. Thus, after compilation, at linking state, compiler sees more than one occurrences of orderOfVoc() which is why compiler is complaining.
Solution:
You remove different definition of orderOfVoc() function. Make use of the user selected value. Pass the value to the orderOfVoc() as an argument, and execute accordingly.
Secondary Issue(s): Apart from above issue(s), in your code, with a definition like
char selectLang[1];
writing
scanf("%d",&selectLang[1]);
is wrong, because
selectLang[1] is out of bound access. Array index in C starts from 0.
%d is not the correct formart specifier for char.
FWIW, char selectLang[1]; is functionally equivalent with char selectLang;
A modified version (not tested) for aforesaid approach:
select_menue.h
#ifndef SELECT_MENUE_H //include guards
#define SELECT_MENUE_H
//according to {store 1 for English or 2 for German}
#define ENGLISH 1
#define GERMAN 2
extern int orderOfVoc(int);
#endif //SELECT_MENUE_H
select_menue.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "select_menue.h"
int orderOfVoc(int lang)
{
int selectOrder = 0;
switch (lang)
{
case ENGLISH:
printf("How do you want to learn the vocabulary?\n(1) - Vocabulary in order\n(2) - Random order\n");
scanf("%d",&selectOrder); //add possible error check
break;
case GERMAN:
printf("Wie sollen die Vokabeln abgefragt werden?\n(1) - Der Reihe nach\n(2) - Zufaellig\n");
scanf("%d",&selectOrder); //add possible error check
break;
}
return selectOrder;
}
vocTrainer.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "select_menu.h"
int main(void)
{
int selectLang = 0; //array not required, initialize in single statement
//store 1 for English or 2 for German
while(selectLang != 1 && selectLang != 2)
{
//select your language
printf("Choose language - Sprache auswaehlen:\n(1) - Englisch/English\n(2) - Deutsch/German\n");
scanf("%d",&selectLang);
}
printf("Test of select Order: %d",orderOfVoc(selectLang));
return 0;
}
#include is a preprocessor directive that includes the contents of the file named at compile time.
The code that conditionally includes stuff is executed at run time...not compile time. So both files are being compiled in. ( You're also including each file twice, once in the main function and once above it, which is just confusing and probably wrong, but we'll ignore that for now. )
You can't really conditionally include stuff at run time. You can use other preprocessor directives (#ifdef, etc. ) to conditionally include one or the other file at compile time, but for your purposes you really need to have some sort of global flag that each function in the included files uses to determine if it should display english or german, etc.
Internationalization of strings is a whole topic in itself. There are lots of ways to handle it, and some libraries to make it easier depending on your platform.
Here's one way you could handle the same scenari:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "german_menue.h"
char *getLocalizedString(int stringId)
{
// Pseudo-Code, not real C++
// Also ignores memory issues and deallocating strings when done
char *localizedString = LoadGermanOrEnglishStringBasedOnGlobalVarForLanguage(stringId);
return localizedString ;
}
int orderOfVoc()
{
int stringId = 1;//should be constant for this message
char *localizedString = getLocalizedString(stringId);
printf("%s", localizedString);
scanf("%d",&selectOrder[1]);
return selectOrder[1];
}
I would like to report an intriguing bug I have. The piece of code below is supposed to print out 20 times "1.0". Instead, when compiling with icc (11.1) on my mac (snow leopard 10.6.8), I get unstable values (16 times "0.0" then 4 times "1.0"). I make use of several features in the code but none of them seems to have a bad syntax (no error during compilation, and valgrind reports no error during running). However if I change anything (even non used function - that's why I find it very strange), I get the correct output. Compiling with gcc gives the correct output as well.
But I think the strangest thing is that if I delete the function "function1", the bug disappears, although the function is NOT used in the code.
This is really odd, and now I fear that my code (which is much bigger than that) will be unstable. I need your help, I'm really puzzled by this. Is there anything wrong in the syntax?
main.c:
#include "main.h"
int main(argc,argv)
int argc;
char **argv;
{
Config para;
para.option1 = ONE;
para.a[0] = 0.0;
para.a[1] = 0.0;
para.a[2] = 0.0;
para.a[3] = 1.0;
int i;
double *x = (double *)malloc(20*sizeof(double));
for(i=0;i<20;i++) x[i] = 1.0;
for(i=0;i<20;i++) printf("%f \n", x[i]);
free(x);
function2(para);
return EXIT_SUCCESS;
}
void function1(int option){
switch(option){
case ONE: case TWO: case THREE: case MONE:
printf("MONE to THREE\n");
break;
case FOUR:
printf("FOUR\n");
break;
}
return;
}
void function2(const Config para){
if(para.option1 == FOUR){
printf("FOUR\n");
}
return;
}
main.h:
#include <string.h>
#include <stdio.h>
#include <stddef.h>
#include <math.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <stdarg.h>
#define MONE -1
#define ONE 1
#define TWO 2
#define THREE 3
#define FOUR 4
typedef struct Config
{
int option1, option2;
double a[4];
} Config;
void function1(int option);
void function2(const Config para);
When digging more on the web, I found this bug report from Intel:
http://software.intel.com/en-us/articles/intel-compiler-and-xcode-322-linker-runtime-crash-with-switch-statement/
It seems to be related to how the icc compiler optimizes case statements. Their suggestions to solve the problem are the following:
1) Use Xcode 3.2.1 with 11.1 compiler.
2) Use 11.1 compiler with the option -use-asm with Xcode 3.2.2, 3.2.3, 3.2.4.
It should fix most cases but there are some cases when even generating object file through external assembler L* symbols still may appear in object file. Those cases are usually constant string literals placed in cstring section
3) Use Intel Composer XE.
My Xcode is version 3.2.6, but solution 2) solved my problem. I remain however quite puzzled about this (and the lack of documentation on the web).
Thanks.