繁体   English   中英

使用C / C ++计算整数和浮点数

[英]Calculating with integers and floating point numbers using c/c++

我的以下代码有问题:

#include <stdio.h>
#include <iostream>

int main () 
{
 int a, b;

 printf("Please type in your number a: ");
 scanf_s("%d", &a);

 printf("Please type in your number b: ");
 scanf_s("%d", &b);

 printf("Solution 1 (divide and modulus): %f\n", a / b +  a % b); 
 printf("Solution 2 (cast): %f", (float) a / b); 

 std::cin.get(); 
 std::cin.get(); 

 return 0;

}

我希望我的程序读取两个整数,并且我想使用两种不同的方法对它们进行除法,而不会出现舍入错误。 诚然,第一个解决方案不起作用。 输出仅为零。 我不知道问题出在哪里。

a/b + a%binteger%d ),但是您正在打印float%f )。

我认为应该是:

a/b + (a%b)/(float)b

你应该改变

 printf("Solution 1 (divide and modulus): %f\n", a / b +  a % b); 

 printf("Solution 1 divide %i modulus %i \n", a / b,  a % b); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM