无论用户输入如何,将输入转换为int
发布时间:2020-12-16 09:20:45 所属栏目:百科 来源:网络整理
导读:我有以下c代码,并希望确保即使用户输入一个浮点数,这将转换为int. #include stdio.h#include stdlib.h#include string.h#include math.hint main(){ int i,times,total; float average = 0.0; int * pArr; printf("For how many numbers do you want the ave
我有以下c代码,并希望确保即使用户输入一个浮点数,这将转换为int.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int main() { int i,times,total; float average = 0.0; int * pArr; printf("For how many numbers do you want the average calculated?n"); scanf("%d",×); pArr = (int *) malloc(times * sizeof(int)); printf("Please enter them down heren"); for(i=0;i<times;i++) { scanf("%d",&pArr[i]); total += pArr[i]; } average = (float) total / (float) times; printf("The average of your numbers is %.2fn",average); return 0; } 所以现在的问题是,当用户输入一个浮点数时,程序就会终止.任何线索? 解决方法
scanf遇到点时会停止扫描.因此无法直接扫描输入.
但您可以通过扫描字符串,然后扫描字符串中的整数来解决它.这是错误的错误检查,但至少它会丢弃浮动部分,你可以输入浮点数或整数(还要注意总数没有初始化,gcc -Wall -Wextra甚至没有检测到). 找到下面的工作版本(虽然输入整数时需要更多的错误检查): #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> int main() { int i,total = 0; // don't forget to initialize total to 0 !!! float average = 0.0; int * pArr; char temp[30]; printf("For how many numbers do you want the average calculated?n"); scanf("%d",×); pArr = malloc(times * sizeof(int)); // don't cast the return value of malloc printf("Please enter them down heren"); for(i=0;i<times;i++) { scanf("%29s",temp); // scan in a string first sscanf(temp,"%d",&pArr[i]); // now scan the string for integer total += pArr[i]; } average = (float) total / (float) times; printf("The average of your numbers is %.2fn",average); free(pArr); // it's better to free your memory when array isn't used anymore return 0; } 笔记: >阵列分配&如果你只计算值的平均值,那么存储在这里没用>你没有受到有效浮点指数输入的保护:如果输入1e10,则扫描值1(与另一个可行的答案的“%f”方法相反,但我担心存在风险舍入错误) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |