C&C++   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了无论用户输入如何,将输入转换为int大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_262_0@
@H_262_0@
我有以下c代码,并希望确保即使用户输入一个浮点数,这将转换为int.

#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",&times);

  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;
}

所以现在的问题是,当用户输入一个浮点数时,程序就会终止.任何线索?

解决方法

scanf遇到点时会停止扫描.因此无法直接扫描输入.

但您可以通过扫描字符串,然后扫描字符串中的整数来解决它.这是错误错误检查,但至少它会丢弃浮动部分,你可以输入浮点数或整数(还要注意总数没有初始化,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",&times);

  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”方法相反,但我担心存在风险舍入错误)

@H_262_0@

大佬总结

以上是大佬教程为你收集整理的无论用户输入如何,将输入转换为int全部内容,希望文章能够帮你解决无论用户输入如何,将输入转换为int所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签:int如何无论用户转换输入
猜你在找的C&C++相关文章
其他相关热搜词更多
phpJavaPython程序员load如何string使用参数jquery开发安装listlinuxiosandroid工具javascriptcap