2013-09-21 35 views
0

/* 3/4下一頁下一頁我有本段下面直接列出的代碼。我需要它來打印剩下的部分,但似乎無法正確完成。我知道使用模運算符是這個函數的關鍵,但是我對如何正確使用它失去了興趣。如何使用printf輸出中division的模運算符以下列方式顯示餘數:C

result = num1/num2;     /* Division */ 
printf("When 63 is divided by 6 you get %i\n\n", result); 

*/

#include <stdio.h> 

int main(void) 
{ 

    int  num1 = 63; 
    int  num2 = 6; 
    int  result; 

    float nickels = 0.05; 
    float pennies = 0.01; 
    float nickPen;      /* I really wasn't sure rather to add nickPen as a float or to even add it at all */ 


    printf("This program will do a few computations with two numbers.\n\n"); 

    printf("The two numbers used by this program are 63 and 6.\n\n"); 

    result = num1 + num2;     /* Addition */ 
    printf("The sum of 63 + 6 is %i\n", result); 

    result = num1 - num2;     /* Subtraction */ 
    printf("The difference of 63 - 6 is %i\n", result); 

    result = num1 * num2;     /* Multiplication */ 
    printf("The product of 63 * 6 is %i\n", result); 

    result = num1/num2;     /* Division */ 
    printf("When 63 is divided by 6 you get %i\n\n", result); 

    nickPen = nickels*100 + pennies*25;  /* Multiplication and addition of money */ 
    printf("If you have 100 nickels + 25 pennies you will have $%.2f\n\n", nickPen); 

    printf("Thank you for using this program"); 



     getchar(); 
     return 0; 

} /* End Main*/ 
+0

'result = num1%num2;'不會削減它? –

回答

0
printf("When 63 is divided by 6 the remainder is %i\n\n", 63 % 6); 
0

模中C是x % y其中模定義爲x - ((int)x/y)*y

+0

'%'操作符不涉及將'x'轉換爲'int'。 –

0
result = num1 % num2; /* Modulus */ 
printf("When 63 is divided by 6 you get a remainder of %i\n\n", result);