无论用户输入如何,将输入转换为int

时间:2018-05-11 21:25:20

标签: c

我有以下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", &times);

  pArr = (int *) malloc(times * sizeof(int));

  printf("Please enter them down here\n");

  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 %.2f\n", average);

  return 0;
}

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

2 个答案:

答案 0 :(得分:4)

scanf会在遇到点时停止扫描。因此,直接扫描输入是不可能的。

但您可以通过扫描字符串来解决此问题,然后扫描字符串中的整数。这是错误的错误检查,但至少它会丢弃浮动部分,你可以输入浮点数或整数(还要注意total没有初始化,gcc -Wall -Wextra没有甚至检测到了。)

找到下面的工作版本(虽然输入整数时需要更多错误检查):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>

int main()
{
  int i, times, 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", &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
    total += pArr[i];
  }

  average = (float) total / (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;
}

注意:

  • 阵列分配&amp;如果你只计算值的平均值,那么存储在这里并不有用。)
  • 您未受到有效浮点指数输入的保护:如果输入1e10,则会扫描值1(而不是其他答案的"%f"方法这会有效,但我担心有风险舍入错误)

答案 1 :(得分:2)

如果您不希望将用户输入四舍五入到最近的int,则只需将其作为float读取,然后转换为int。

float in = 0.0f;
scanf("%f", &in);   // Read as float
pArr[i] = (int) in; // Cast to int