练习30
编写一个程序,读取以十进制扩展名开发的浮点值和
记住数据控制
这是没有关于整数类型的消息的新消息。
#include <stdio.h>
#include <math.h>
int main(){
double x; //the argument of f(x)
printf("Program demands x");
printf("\nand writes the rounded value\n");
printf("Author: xXx\n\n");
//loading data
printf("Write x in float type in decimal extension "); // after many tries, program is not rounding the value
if (scanf("%lf",&x)!=1 || getchar()!='\n'){
printf("Wrong data.\n");
printf("\nEnd of program.\n");
return 0;
}
double round( double x );
printf( "Rounded value is = %lf\n", x);
printf("\nEnd of program.\n");
return 0;
}
答案 0 :(得分:7)
保持简单:
将输入作为字符串读入缓冲区fgets(buffer, BUFFER_SIZE, stdin);
使用sscanf
尝试读取整数:
int i, r, n;
r = sscanf(buffer, "%d%n", &i, &n);
if(r == 1 && n == strlen(buffer)) {
// is integer
}
此处的额外长度检查是为了确保评估所有字符,12.3
之类的数字将不被接受为12
。
如果上一步失败,请尝试阅读浮点数:
double dbl;
r = sscanf(buffer, "%lf", &dbl);
if(r == 1) {
// is double
}
答案 1 :(得分:3)
我建议如下:
val
,比如说。val
的整数部分放入int变量truncated
,比如说。val
和truncated
是否相等。该功能可能如下所示:
bool isInteger(double val)
{
int truncated = (int)val;
return (val == truncated);
}
如果val
超出可以存储在int
中的值范围,您可能需要添加一些完整性检查。
请注意,我假设您要使用数学家的整数定义。例如,此代码将"0.0"
视为指定整数。
答案 2 :(得分:0)
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main() {
char buffer[128], *p = buffer;
int isint;
fgets(buffer, sizeof buffer, stdin);
if (p[0] == '+' || p[0] == '-')
p++;
isint = strlen(p) - 1;
for (; *p && *p != '\n' && isint; p++) {
isint = isdigit(*p);
}
if (isint)
printf("Woaaa\n");
return 0;
}
基于比较输入字符串和使用扫描整数创建的字符串的稍微清洁版本:
#include <stdio.h>
#include <string.h>
int main() {
char buffer[128], tostr[128];
int d;
fgets(buffer, sizeof buffer, stdin);
buffer[strlen(buffer) - 1 ] = 0;
sscanf(buffer, "%d", &d);
sprintf(tostr, "%d", d);
if (!strcmp(buffer, tostr)) {
printf("Woa\n");
}
return 0;
}
答案 3 :(得分:0)
我建议您可以通过字符串获取输入并检查它是浮点数还是整数。
例如:
#define IS_FLOAT = 1;
#define IS_INT = 2;
int main()
{
char tempString[20];
scanf("%s", tempString);
if(checkType(tempString)==IS_INT)
printf("This is integer\n");
else if(checkType(tempString)==IS_FLOAT)
printf("This is Float");
else
printf("undifined");
}
int checkType(char *input)
{
short int isInt=0;//we use int as a boolean value;
short int isFloat=0;
short int isUndifined=0;
int count;
for(count = 0 ; input[count ]!='\0'; count++)
{
if(isdigit(input[count]))//you should include ctype.h at the beginning of this program
isInt=1;
else if(input[count] == '.')
isFloat=1;
else
return -1;//some character that neither int nor '.' char.
}
if(isInt == 1 && isFloat ==1)
return IS_FLOAT;
else if(isInt == 1 && isFloat ==0)
return IS_INT;
else
return -1;//illegal format
}