C. 检查特定小数位数的浮点数输入

C. Check input of a float for a certain number of decimal places

早上好。我编写的代码用于计算交易中给出的找零金额,仅找零部分,忽略纸面找零。我想做一个错误检查以确保用户输入的 # 不超过 2 个小数位。这是我的代码。

#include <stdio.h>
#include <stdlib.h>
void intro();
void instructions();
void getvalues(float *owe, float *paid);
float totalchange(float *owe, float *paid);
void quarters (float *change);
void dimes (float *change);
void nickels (float *change);
void pennies (float *change);

int main()
{
    float owe = 0.0, paid = 0.0, change;
    int a = 2;
    intro();
    instructions();

        printf("Would you like to continue?\n1: Continue\n0: Exit\n");
        scanf("%i", &a);
        if (a== 0)
            exit(0);

        while (a == 1){
            getvalues(&owe, &paid);
            while (owe > paid)
                getvalues(&owe, &paid);
            change = totalchange(&owe, &paid);
            quarters (&change);
            dimes (&change);
            nickels (&change);
            pennies (&change);

            printf("Would you like to make another calculation?\n1: Continue\n0: Exit\n");
            scanf("%i", &a);
    }

    return 0;
}

void intro(){
    printf("Program: Homework 1 Part 1 :: Change Calculator\nAuthor: Jason Golightly\nDate:5-13-15\nVersion 1.0\n\n");
}


void instructions(){
    printf("This program is designed to calculate the coin\nportion of the change given after a purchase.\n");
    printf("When prompted, please enter the purchase amount and the amount paid.\nThe amount paid must exceed the purchase amount.\n");
}

void getvalues(float *owe, float *paid){

        printf("Please enter the amounts in a dollars.cents fashion\n\nPurchase amount?\n");
        scanf("%f", owe);
        printf("\nAmount paid?\n");
        scanf("%f", paid);
        printf("\n");
        if (*owe > *paid)
            printf("ERROR. Please enter valid amounts.\n");
        if (*owe == *paid)
            printf("You have given exact change.\n")

}

float totalchange(float *owe, float *paid){
    int a;
    a = (*paid - *owe)*100;
    a = a % 100;
    printf("total change = %i\n",a);
    return a;
}
void quarters (float *change){
    int q;
    q = *change / 25;
    printf("Quarters = %i\n", q);
    *change = *change - 25*q;
}
void dimes (float *change){
    int d;
    d = *change / 10;
    printf("Dimes = %i\n", d);
    *change = *change - 10*d;
}

void nickels (float *change){
    int n;
    n = *change / 5;
    printf("Nickels = %i\n", n);
    *change = *change - 5*n;
}
void pennies (float *change){
    int p;
    p = *change / 1;
    printf("Pennies = %i\n\n", p);
    *change = *change - 1*p;
}

此外,如果您没有注意到,我对编程还很陌生。如果您看到其他我可以做得更好的地方,请随时指出。

谢谢杰森

避免不精确浮点计算的简单方法是将输入读取为字符串,将其解析为 int,并将其显示为 *.##

char number[11];
scanf("%10s", number);
int actual_number = parse(number); // parse the string here.

这个实际数字基本上是美元*100 + 美分 - 这是一个 int。 现在执行所有计算并显示如下:

float f = (float)actual_number/100.f ;
printf("%.2f", f);

parse例程中,遇到.

后只考虑前两位

Here 是 C 中解析例程的一个例子。