Question

In: Computer Science

Can anyone fix this code? The code isn't rounding the answer to the nearest whole number...

Can anyone fix this code? The code isn't rounding the answer to the nearest whole number like 2.345 should be 2 and 2.546 should be 3 but the round() function isn't working as expected. The round() function is rounding 2.546 to 2 which is incorrect since 4 and below should be rounded to 2 and 5 and above should be rounded to 3.

Here is the code:

#importing xlwt library to write into xls
import xlwt
from xlwt import Workbook

#create a workbook
wb = Workbook()
#create a sheet
sheet = wb.add_sheet('Sheet')

#percentages list
percentages = [23.6, 38.2, 50, 61.8, 78.6, 113, 123.6, 138.2, 161.8]
#add first row
for i in range(len(percentages)):
   sheet.write(0,i+1,str(percentages[i])+'%')

#user input
n = int(input('Enter number of elements: '))
#second row starts from index 1
row=1
print('Enter numbers: ')
for i in range(n):
    #User input
   val = float(input())
   #Add entered value to first column of the row
   sheet.write(row,0,str(val))
   #calculate each percentage
   for j in range(len(percentages)):
       result = (percentages[j]/100)*val
       #write result to sheet by rounding upto 3 decimal points
       sheet.write(row,j+1,str(round(result,3)))
   #increment the row by 1
   row+=1
#save Workbook as xls`
wb.save('percentages.xls')

Thank you so much for anyone who helped!

Solutions

Expert Solution

I have showed some sample on how round function behaves.. It has a second argument which signfies the level of rounding on how many digits you want after decimal.. In your case, You want 2.5 or more to be rounded as 3, while 2.4999999999 and below to be 2.. Which means, You do not want a digit after decimal.. Hence you should call round function with second argument as 0.. which will give you desired result.. Below is complete code:

#importing xlwt library to write into xls
import xlwt
from xlwt import Workbook

#create a workbook
wb = Workbook()
#create a sheet
sheet = wb.add_sheet('Sheet')

#percentages list
percentages = [23.6, 38.2, 50, 61.8, 78.6, 113, 123.6, 138.2, 161.8]
#add first row
for i in range(len(percentages)):
   sheet.write(0,i+1,str(percentages[i])+'%')

#user input
n = int(input('Enter number of elements: '))
#second row starts from index 1
row=1
print('Enter numbers: ')
for i in range(n):
    #User input
   val = float(input())
   #Add entered value to first column of the row
   sheet.write(row,0,str(val))
   #calculate each percentage
   for j in range(len(percentages)):
       result = (percentages[j]/100)*val
       #write result to sheet by rounding upto 3 decimal points
       sheet.write(row,j+1,str(round(result,0)))
   #increment the row by 1
   row+=1
#save Workbook as xls`
wb.save('percentages.xls')
**************************************************

Thanks for your question. We try our best to help you with detailed answers, But in any case, if you need any modification or have a query/issue with respect to above answer, Please ask that in the comment section. We will surely try to address your query ASAP and resolve the issue.

Please consider providing a thumbs up to this question if it helps you. by Doing that, You will help other students, who are facing similar issue.


Related Solutions

When doing your calculations, round to the nearest whole dollar amount AND the nearest whole number...
When doing your calculations, round to the nearest whole dollar amount AND the nearest whole number of shares,  Enter your answers in whole dollar amounts, without '$' signs and without commas. This fact pattern spans three years. All eight requirements are based on this fact pattern. However, #1 only asks the balance in the Common Stock account at the end of Year 2.  ●Issuance of Shares: Company issued 6,000 common shares with a $10 per share par value for $95,000...
I know the code isn't here nut please answer as much as you can thanks! it...
I know the code isn't here nut please answer as much as you can thanks! it is qt creator c++ Question 1 Which of the following is a correct description of ItemList ? It is a QMap and thus an ItemList object is a QMap itself It has a QMap, which cannot be accessed outside this class ItemList uses a heap QMap object QMap used by ItemList uses Item pointers as keys Question 2 Which of the following is true...
Can you fix the code and comment the fix Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -39 at...
Can you fix the code and comment the fix Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -39 at CaesarCipher.encrypt(CaesarCipher.java:28) at CaesarCipher.main(CaesarCipher.java:52) public class CaesarCipher{     char[] encoder = new char[52];     char[] decoder = new char[52];      public CaesarCipher(int rotation)      {        for(int k=0 ; k < 26 ; k++)        {            encoder[k] = (char) ('A' + (k + rotation) % 26);            decoder[k] = (char) ('A' + (k - rotation + 26) % 26);        }        for(int j...
1) Please solve for the question marks (round to the nearest whole number where applicable):   P.V....
1) Please solve for the question marks (round to the nearest whole number where applicable):   P.V. Years Interest Rate Compounding F.V. A) ? 5 14% Monthly $3,725 B) $235 2 ? Semiannual $935 C) $6,250 8 6 3/4% Simple ? D) $3,750 ? 3 1/2% Annual $8,315   E). $1,075. 3   19% Weekly ? F) Explain the differences between simple and compounded interest rates in light of the results you attained.
Find the mean, median, mode, and standard deviation (round standard deviation to the nearest whole number)...
Find the mean, median, mode, and standard deviation (round standard deviation to the nearest whole number) for the following SAMPLE set of test scores.             90 85 75 70 80 80 Using the above information and the Empirical Rule: What percent of scores would you expect to fall between 66 and 87?                    ____________ 68% of the time you would expect scores between what two values?                     ____________ Determine the z-score for a test score of 64.                                                             ____________...
Do not round intermediate calculations and round your answers to the nearest whole number, e.g., 32....
Do not round intermediate calculations and round your answers to the nearest whole number, e.g., 32. A negative answer should be indicated by a minus sign. Problem: Project Evaluation Suppose you have been hired as a financial consultant to Defense Electronics, Inc. (DEI), a large, publicly traded firm that is the market share leader in radar detection systems (RDSs). The company is looking at setting up a manufacturing plant overseas to produce a new line of RDSs. This will be...
Can you fix the errors in this code? package demo; /** * * */ import java.util.Scanner;...
Can you fix the errors in this code? package demo; /** * * */ import java.util.Scanner; public class Booolean0p {        public class BooleanOp {            public static void main(String[] args) {                int a = 0, b = 0 , c = 0;                Scanner kbd = new Scanner(System.in);                System.out.print("Input the first number: ");                a = kbd.nextInt();                System.out.print("Input...
Can someone fix this code so that it can count comparison and exchange? import java.util.Arrays; class...
Can someone fix this code so that it can count comparison and exchange? import java.util.Arrays; class Main { static int comparisons; static int exchanges; // Recursive function to perform insertion sort on sub-array arr[i..n] public static void insertionSort(int[] arr, int i, int n) { int value = arr[i]; int j = i; // Find index j within the sorted subset arr[0..i-1] // where element arr[i] belongs while (j > 0 && arr[j - 1] > value) { arr[j] = arr[j...
How can I fix this code to accomplish the goal of reading and writing on binary...
How can I fix this code to accomplish the goal of reading and writing on binary or text files? 3 import java.io.*; 4 import java.io.FileOutputStream; 5 import java.io.FileInputStream; 6 import java.util.Scanner; 7 8 public class ReadAndWrite implements Serializable 9 { 10 public static void main(String[] args) 11 { 12 boolean file = true; 13 Scanner inputStream; 14 PrintWriter outputStream; 15 FileInputStream inputBinary; 16 FileOutputStream readBinary; 17 FileInputStreamText writeText; 18 FIleOutputStreamText readText; 19 StringBuffer contents = new StringBuffer(); 20 Scanner keyboard...
a. Find a 90% confidence interval for s=37 x=1278 n=9. Round to nearest whole number b....
a. Find a 90% confidence interval for s=37 x=1278 n=9. Round to nearest whole number b. Find a 99% confidence interval for s=3.5 x=15.8 n=10.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT