[英]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%b
是integer
( %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.