我如何转换浮球随模在C诠释? [英] How Can I Convert Float to Int with Modulus in C?

查看:105
本文介绍了我如何转换浮球随模在C诠释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑与模量C.我写一个小脚本,可以让用户输入他们的两个号增值经销商,那么他们可以加,减,乘,除(容易)或模量(有没有中招这其中还)。什么会我做错了在这?我得到的无效的操作数为二进制%的错误,这意味着我需要的,因为它是一个浮动对其进行格式化为int。然而什么是以下这样做的最佳方式?任何C帮助将不胜AP preciated。

I am so confused with Modulus in C. I am writing a small script that allows the user to input their two number vars, then they can either add, subtract, multiply, divide (easy) or modulus (haven't caught this one yet). What would I be doing wrong in this? I get the "invalid operands to binary %" error, which means I need to format it to an int since it is a float. However what is the best way of doing this with the following? Any C help would be greatly appreciated.

int main (void)
{
    float number1, number2, result;
    char symbol;

    //allow user interaction
    printf("Enter your formula: \n");
    scanf("%f %c %f", &number1, &symbol, &number2);



    switch (symbol) {
    	case '%':
    		result = number1 % number2;
    		printf("Result: %f \n", result);
    		break;
    	default:
    		printf("Operation Error. Program aborted. \n \n");
    		break;
    }

    printf("Press any key to continue \n");

    getchar();
    return 0;
}

在哪里,我怎么转换呢?

Where and how do I convert this?

推荐答案

您可以使用如下语句:

result = (int)number1 % (int)number2;

要投你的花车以整数并执行模操作,但你会失去小数precision。

to cast your floats to ints and perform the modulus operation, but you'll lose the decimal precision.

您还可以包括文件math.h和使用FMOD

You could also include math.h and use fmod

result = fmod(number1, number2);

这篇关于我如何转换浮球随模在C诠释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆