我正在研究一种贪婪算法,在将 float 转换为 int 时遇到错误
#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
float n;
//checking if given input is valid or not
do
{
n = get_float();
}
while(n<0);
//converting dollar into cents
float coins = n * 100;
int x = atoi(coins) //getting error here???
....
}
最佳答案
atoi
函数用于将字符串转换为整数。它需要一个 char *
作为指向字符串的参数。
这里不需要转换函数。您可以将 float
值直接分配给 int
,任何小数部分都将被截断。
int x = coins;
但请注意,这可以调用 undefined behavior如果 coins
的截断值超出了 int
的范围。
关于c - 错误: passing 'float' to parameter of incompatible type 'const char *' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55368971/