I'm trying to switch the decimal and real part of a number that the user inputs. So far I'm able to get the program to work for numbers like 123.456 (output should be 456.123) and 123 (output should be .123), however when the user inputs something like .123, the output needs to be 123., which I can't seem to get. Can anyone help me? Here is my code so far:
int i = 0, decimal = 0;
char number[30], realPart[30], fakePart[30];
scanf("%s", number);
for (i = 0; i < 30; i ){
if (number[i] == '.'){
decimal = i;
}
}
for (i = 0; i < 30; i ){
if (decimal == '\0'){
fakePart[i] = '\0';
}
else{
fakePart[i] = number[decimal 1];
decimal ;
}
}
for (i = 0; i < 30; i ){
if(number[i] == '.'){
break;
}
else{
realPart[i] = number[i];
}
}
CodePudding user response:
First loop finds if there is a decimal point and if so where is it
Your issue is that you treat 'decimal == 0' as meaning no decimal point found. BUT what happens if the input is ".123" then decimal will be 0! So the rest of you code thinks there is no decimal. This is the cause of your error. If you want to keep the same structure of code set decimal to -1 to mean 'no period' before the loop.
Other errors / issues
Dont do
if (decimal == '\0')
it works but readers will think that decimal is a character and that you are looking for the end of string (I did). Just say
if (decimal == 0)
Dont loop till 30, loop to strlen(number)
CodePudding user response:
This isn't a complete answer, but it should be enough to get you started: if the number is already a string, just use strtok(number,".")
to get the pieces on either side of the decimal point.