在C中使用getchar()时,您将获得输入字符的ascii值。如果您需要循环使用getchar()输入的值并将输入的数字(包括'。')转换为浮点数,那么如何转换该值以及根据用户想要输入的值来读取多行?到目前为止,我设法通过使用带有计数器的while循环来检查用户输入他们想要转换为浮点数的值。我的问题是使用内部循环将getchar()中的值一次转换为float,其中数字最终被格式化为浮点数。有什么想法吗?
char input;
float value;
int count = 0;
int i = 0;
scanf("%i", count)
while(i < count)
{
input = getchar();
while(input != '\n')
{
input = input - '0';
printf("%d",value);
}
i++;
}
我在读入后遇到无限循环或0.0值。任何想法?
答案 0 :(得分:0)
根据评论中提到的实际问题,我编辑了代码并根据您描述的内容编写代码。
#include<stdio.h>
void main()
{
int count = 0;
int i = 0;
int count_digits=0;
char output[50]; //For storing the input
scanf("%d",&count);
while(i < count)
{
printf("\n\nInput:%d ",i+1); //For printing the input number.
scanf("%s",&output); //taking input as a String
int char_no=0; //character no pointer
count_digits=0; //for counting number of characters (in our case : Digits) before decimal points which is then to be printed after decimal points
while(output[char_no]!='\0' && output[char_no]!='.') //printing all digits before decimal point or print whole number if it doesn't contain decimal point
{
printf("%c",output[char_no]); //printing character(Digit)
char_no++; //incrementing character number
count_digits++; //Counting total number of digits before decimal point
}
if(output[char_no]!='\0') //If it is not the end of character array means number contains decimal point
{
printf("%c",output[char_no]); //printing decimal point as a character
char_no++; //Incrementing character pointer
}
else
printf("."); //If number doesn't contain decimal point it will print it.
while(count_digits>0 && output[char_no]!='\0') //loop will run till no of digits after decimal point gets printed or reaching at the end of input
{
printf("%c",output[char_no]); //printing the character as it is
char_no++; //incrementing character number
count_digits--; //decrementing total no of digits to be printed after decimal point as one character gets printed.
}
while(count_digits>0) //if input ends but still the no of digits after decimal points are less than the no. of digits before decimal points, It will print zeros to make no.of digits after and before decimal points equal
{
printf("0"); //printing 0
count_digits--; //decrementing total no of digits to be printed after decimal point as one character gets printed.
}
i++;
}
}
上面的