#include <stdio.h> #include <stdlib.h> #include <String.h> #include <math.h> int main() { int i,times,@R_947_10586@l; float average = 0.0; int * pArr; printf("For how many numbers do @R_944_8337@ant the average calculated?\n"); scanf("%d",×); pArr = (int *) malloc(times * sizeof(int)); printf("Please enter them down here\n"); for(i=0;i<times;i++) { scanf("%d",&pArr[i]); @R_947_10586@l += pArr[i]; } average = (float) @R_947_10586@l / (float) times; printf("The average of your numbers is %.2f\n",averagE); return 0; }
但您可以通过扫描字符串,然后扫描字符串中的整数来解决它.这是错误的错误检查,但至少它会丢弃浮动部分,你可以输入浮点数或整数(还要注意总数没有初始化,gcc -Wall -Wextra甚至没有检测到).
#include <stdio.h> #include <stdlib.h> #include <String.h> #include <math.h> int main() { int i,@R_947_10586@l = 0; // don't forget to initialize @R_947_10586@l to 0 !!! float average = 0.0; int * pArr; char temp[30]; printf("For how many numbers do @R_944_8337@ant the average calculated?\n"); scanf("%d",×); pArr = malloc(times * sizeof(int)); // don't cast the return value of malloc printf("Please enter them down here\n"); 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 @R_947_10586@l += pArr[i]; } average = (float) @R_947_10586@l / (float) times; printf("The average of your numbers is %.2f\n",averagE); free(pArr); // it's better to free your memory when array isn't used anymore return 0; }
笔记:
>阵列分配&如果你只计算值的平均值,那么存储在这里没用>你没有受到有效浮点指数输入的保护:如果输入1e10,则扫描值1(与另一个可行的答案的“%f”方法相反,但我担心存在风险舍入错误)
以上是大佬教程为你收集整理的无论用户输入如何,将输入转换为int全部内容,希望文章能够帮你解决无论用户输入如何,将输入转换为int所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。