如何解决我怎样才能制作一个只接受数字和字符“.”的字符串?在 c?
我正在尝试用 c 编写一个程序来检测一个数字是整数还是浮点数,如果它是一个浮点数,则计算小数位数。
但是我在这里遇到了一个问题,当我插入一个浮点数时,因为“。”程序说它是一个“单词”而不是数字,因为我让它只接受数字并且我陷入了 while 循环。
我的代码:
#include<stdio.h>
#include <string.h>
#define BASE 10
main()
{
int length,number;
char str[10];
char ch = '.';
char *ret;
char *endptr;
do{
printf("Enter string: ");
scanf("%s",str);
number = strtol(str,&endptr,BASE);
}while (*endptr != '\0' || endptr == str);
ret = strchr(str,ch);
if(ret > 0){
length = strlen(ret);
printf("decimal places: %d\n",length - 1);
}
else {
printf("the number is integrer\n");
}
return 0;
}
解决方法
只有当您知道输入是整数时,使用 start_character = "A"
end_character = "Z"
#You may modify the lines of code above,but don't move them!
#When you Submit your code,we'll change these lines to
#assign different values to the variables.
#Print all the letters from start_character to end_character,#each on their own line. Include start_character and
#end_character themselves.
#
#Remember,you can convert a letter to its underlying ASCII
#number using the ord() function. ord("A") would give 65.
#ord("Z") would give 90. You can use these values to write
#your loop.
#
#You can also convert an integer into its corresponding ASCII
#character using the chr() function. chr(65) would give "A".
#chr(90) would give "Z". So,for this problem,you'll need
#to convert back and forth between ordinal values and
#characters based on whether you're trying to loop over
#numbers or print letters.
#
#You may assume that both start_character and end_character
#are uppercase letters (although you might find it fun to
#play around and see what happens if you put other characters
#in instead!).
#Add your code here! With the original values for
#start_character and end_character,this will print the
#letters from A to Z,each on their own line.
for char in range(ord(start_character),ord(end_character)):
for h in chr(char):
print(h)
才有意义。如果您知道输入是浮点数,则可以改用 strtol
。没有函数可以同时处理这两种类型,除非您想将整数作为浮点数处理。
为了确定输入是整数、浮点数还是无效输入,最好自己检查输入字符串,例如像这样:
strtod
注意这个程序还会统计遇到的位数,并在程序结束时打印总数。既然您在问题中表示要计算“小数位数”,那么这可能就是您想要的。
另请注意,此程序不接受指数表示法的浮点数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。