【发布时间】:2017-02-25 12:50:38
【问题描述】:
在一项学校作业中,我们应该编写一个程序,该程序接收一个数字并将其分为三个部分: 1.检查数字是正数还是负数 2.整数(大小) 3. 小数部分
要求应该有一个自己的函数,称为separate,具有输入和输出参数。
例如:如果您输入 23.639,程序应该排序并打印出: 签名:+ 整数大小:23 小数部分:0.639
问题: 1.数字正负分拣功能,输入负数时出现错误答案。它还发布了错误的字符。我尝试过不同的数据类型,如 int、char 和 float,但似乎都不起作用。非常感谢任何有关如何解决此问题的提示,因为我认为我被自己的错误蒙蔽了双眼......
2.将小数与整数(分数)分开的函数不会从小数中减去整数,所以我被整数困住了。谁能在这里发现我的错误?
* 更新 *
我设法解决了手头的问题,并且在编辑我在这个问题中首次发布的代码时出现了可怕的 n00b 错误。 我现在再次编辑了代码,以尽我所能保存原始错误。正确的代码作为答案发布在下面。
抱歉,新手错误。
/*
Author: Thorbjørn Elvestad
Student ID: *****
E-mail: drommevandrer@gmail.com
This program take in number typed in by the user, and then divide it into three parts.
SIGN: '+' or '-'
Whole number: Show number as a whole number
Fraction: Show fractions
The program uses function to sort out the number, and print out the result*/
/* Declaring libraries */
#include <stdio.h>
#include <stdlib.h>
/* Declaring functions */
double sorting_sign(char x);
double sorting_whole(double x);
double sorting_fract(double x, int y);
/* Calling main function */
int main()
{
double num, fractures; /* declaring variables */
int sign_sorted, part;
double whole_sorted;
printf("LET ME TELL YOU SOME INTERESTING STUF ABOUT YOUR NUMBER!\n\n");
printf("Enter your number: ");
scanf("%d", &num);
sign_sorted = sorting_sign(num); /* Calling the function that sorts out if this number is '+' or '-' */
whole_sorted = sorting_whole(num); /* Calling the function separating whole number from decimals */
fractures = sorting_fract(num, num); /* Calling the function removing the whole number from the fractures */
printf("Sign: %c\nWhole: %0.lf\nFraction: %f", sign_sorted, whole_sorted, fractures);
return 0;
}
/* Function for sorting of if number is '+' or '-' */
double sorting_sign(char x)
{
int sign;
/* true if number is less than 0 */
if(x < 0.0){sign = '-';}
/* true if number is greater than 0 */
else if(x > 0.0){sign = '+';}
return (sign);
}
/* Function for sorting out the whole number */
double sorting_whole (double x)
{
int whole;
whole = x;
return (whole);
}
/* Function for sorting out the fractions */
double sorting_fract(double x)
{
int whole;
double fract;
whole = y;
fract = x - whole;
return (fract, whole);
}
【问题讨论】:
-
(fract, whole)是双倍的吗? -
scanf("%d", &num);-->scanf("%lf", &num);和printf("DEBUGGING 1 (in main): Your number is %d ...应该使用类型%f。 -
是的,当然……成功了。谢谢...我有一种感觉,我设法在某个地方遇到了一个数据类型的迷宫,并在我的搜索中弄乱了代码来修复它。但是,我确实认为问题出在函数中,而不是我的 scanf,但这实际上很有意义:)
-
对不起,菜鸟的错误......这两个问题的答案以及包括完整工作程序在内的完整答案发布在下面。